We want to display all the names from our json file into a div using javascript. We tried a lot of things, but we didn't manage to succeed.
json data : http://www.smartbustracking.be/json/data.json
This is what we tried :
<button>get data</button>
<div id="resultJson"></div>
<script type="text/javascript" language="javascript">
$("button").click(function(){
$.getJSON("http://www.smartbustracking.be/json/data.json", function(result){
for(var x = 0; x < result.length; x++){
$.each(result, function(i, field) {
$("#resultJson").append(field[x].name);
}
}
});
});
If anyone can help us with this ploblem, that would be great
Thanks in advance !
don't use extra loop inside for loop to extract name.
Your data is like
[0] = {name:"name1"}
[1] = { name: "name2"}
If there is a array inside [0] and you want to extract value from that then you need another loop inside for loop to extract that value like you wanna to pull value of bushaltes
.
Try like this
$("button").click(function() { $.getJSON("http://www.smartbustracking.be/json/data.json", function(result) { console.log(result); for (var x = 0; x < result.length; x++) { $("#resultJson").append(result[x].name); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>get data</button> <div id="resultJson"></div>
you need either the for
loop or $.each
but not both.
Here's the updated code.
$("button").click(function(){
$.getJSON("http://www.smartbustracking.be/json/data.json", function(result){
$.each(result, function(i, field) {
$("#resultJson").append(field.name);
});
});
});
and here's the demo
I don't see why you are using jQuery each
inside your for
loop.
Additionnaly, I think you should use result[x].name
instead of field[x].name
as you are giving result
as parameter of callback function:
$.getJSON("http://www.smartbustracking.be/json/data.json", function(result){
for(var x = 0; x < result.length; x++){
$("#resultJson").append(result[x].name);
}
});
I hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.