Reputation: 197
I'm new to JS and would like to display in my html file a variable to be parsed from a local JSON file ? I'm running that in Django with bootstrap.
myfile.json contains:
[{"myvar":"1500000"}]
my html template contains:
...
<div class="col-9">
<h3 class="f-w-300 d-flex align-items-center m-b-0"><i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i><span id="output_1"></span></h3>
</div>
...
...
<!-- Specific Page JS goes HERE -->
{% block javascripts %}
{% load static %}
<script src="{% static 'dashboard_data.json' %}">
var my_kpi = fetch("/static/dashboard_data.json")
.then(response => response.json())
.then(data => {
console.log(data.myvar)
document.querySelector("output_1").innerText = data.myvar
});
document.getElementById('output_1').innerHTML = my_kpi
</script>
{% endblock javascripts %}
I'm not sure what I'm doing wrong. From the development tool when debugging in the browser, I can see that the JSON file appears in the sources, but the myvar value does not show in the console nor in the html page. It looks like nothing is being parsed at all inside my_kpi.
Many thanks for your help.
Upvotes: 1
Views: 223
Reputation: 197
I found the solution (thanks to Zsolt Meszaro!)
I was wrongly reading the JSON file as well ... for Django Bootstrap, one should pass inside the fetch() function the follwing command: "{% static filename.json%}"
instead of fetching a standard file path. Make sure your file is in your /static/ directory.
The html code below works just fine now:
...
<div class="col-9">
<h3 class="f-w-300 d-flex align-items-center m-b-0"><i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i><span id="output_1"></span></h3>
</div>
...
...
<!-- Specific Page JS goes HERE -->
{% block javascripts %}
{% load static %}
<script>
fetch("{% static 'dashboard_data.json' %}")
.then(response => response.json())
.then(data => {
console.log(data[0].myvar)
document.querySelector("#output_1").innerText = data[0].myvar
});
</script>
{% endblock javascripts %}
Upvotes: 0
Reputation: 23141
querySelector("output_1")
isn't valid selector and you can't set a pending promise as the innerHTML.
querySelector("output_1")
should be querySelector("#output_1")
if it's the id.
[{"myvar":"1500000"}]
is an array so you can't log like data.myvar
in your promise as it's undefined. data.myvar
should be data[0].myvar
.
fetch('/static/dashboard_data.json')
.then((response) => response.json())
.then((data) => {
console.log(data[0].myvar);
document.querySelector('#output_1').innerText = data[0].myvar;
});
Upvotes: 0