[英]Display JSON data from url using ajax
We want to display all the names from our json file into a div using javascript. 我们希望使用javascript将json文件中的所有名称显示到div中。 We tried a lot of things, but we didn't manage to succeed. 我们尝试了很多事情,但没有成功。
json data : http://www.smartbustracking.be/json/data.json json数据: 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. 不要在for循环中使用多余的循环来提取名称。
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
. 如果[0]中有一个数组,并且您想从中提取值,那么您需要在for循环中使用另一个循环来提取该值,就像您想要提取bushaltes
值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. 你需要无论是for
循环或 $.each
,但不能同时使用。
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);
});
});
});
I don't see why you are using jQuery each
inside your for
loop. 我不明白你为什么要使用jQuery each
你的内部for
循环。
Additionnaly, I think you should use result[x].name
instead of field[x].name
as you are giving result
as parameter of callback function: 另外,我认为您应该使用result[x].name
而不是field[x].name
因为您将result
作为回调函数的参数:
$.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 希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.