Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

Javascript how to pass json content to a variable in Django?

I'm trying to parse a JSON file into a variable, but it would not work for some reason.

If I run the following, it works just fine. I can see the three years printed in the console.

{% block javascripts %}

    <script>

        var mydates = {
            "2018": {
                "January": ["week1","week2","week3","week4"],
                "February": ["week5","week6","week7"],
                "March": ["week8","week9","week11"]
            },
            "2019": {
                "January": ["week1","week2","week3","week4"],
                "February": ["week5","week6","week7"],
                "March": ["week8","week10","week11"]
            },
            "2020": {
                "January": ["week1","week2","week3","week4"],
                "February": ["week5","week6","week7"],
                "March": ["week8"]
            }
        };

        for (let year in mydates){
            console.log(year)
        };

    </script>

{% endblock javascripts %}

However, if I run the following, it doesn't work, the console prints 'undefined'. What am I doing wrong?

{% block javascripts %}
    
{% load static %}
    
<script>
    var mydates;
    fetch("{% static 'dates.json' %}")
    .then(response => {mydates = response.json()
    })
    
    for (let year in mydates){
        console.log(year)
    };

</script>
{% endblock javascripts %}

dates.json is correctly stored in my static folder and it includes the following:

{
   "2018": {
       "January": ["week1","week2","week3","week4"],
       "February": ["week5","week6","week7"],
       "March": ["week8","week9","week10","week11"]
   },
   "2019": {
        "January": ["week1","week2","week3","week4"],
        "February": ["week5","week6","week7"],
        "March": ["week8","week9","week10","week11"]
    },
    "2020": {
        "January": ["week1","week2","week3","week4"],
        "February": ["week5","week6","week7"],
        "March": ["week8","week9","week10","week11"]
    }
}

Many thanks for your help !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...