简体   繁体   English

在javascript中迭代json

[英]iterating through json in javascript

I have an iteration trough json that I cannot make to work. 我有一个迭代通过json我无法工作。

$.post('getdatafromdatabase.php', function(data) {
    var output="<ul> START ";

    for (var i in data.results) {
        output+="<li>" + data.results[i].id + " " + data.results[i].latitude + "--" + data.results[i].longitude+"</li>";
    }

    output+=" END </ul>" + data;
    document.getElementById("bounds").innerHTML += output;
});

The "START" and the "END" does print. “START”和“END”确实打印出来。 Also after the "END" I am printing the "data" out which also works, so I know I am getting the data from the database and it looks like this: 在“结束”之后我打印出的“数据”也有效,所以我知道我从数据库中获取数据,它看起来像这样:

{"results":[{"id":"1","latitude":"47.49882200000000","longitude":"19.05680300000000"},     {"id":"2","latitude":"47.49273300000000","longitude":"19.03345700000000"},{"id":"3","latitude":"47.47765200000000","longitude":"18.98942600000000"},{"id":"4","latitude":"47.47266300000000","longitude":"18.81643700000000"}]}

Can someone please help me with this. 有人可以帮我这个。 I spent a lot of time on this and I can't figure out why can't I get it to print. 我花了很多时间在这上面,我无法弄清楚为什么我不能打印它。 Thanks. 谢谢。

Use 采用

var data = $.parseJSON(data);

before you start looping to read. 在开始循环阅读之前。

Use .ajax instead of $.post 使用.ajax而不是$.post

$.ajax({url:'getdatafromdatabase.php',
        type: "POST",
        data: { name: "John", location: "Boston" }}).done(function(data) {
    var output="<ul> START ";
    for (var i in data.results) {
        output+="<li>" + data.results[i].id + " " + data.results[i].latitude + "--" + data.results[i].longitude+"</li>";
    }
    output+=" END </ul>" + data;
    document.getElementById("bounds").innerHTML += output;
});

this way for iterating through json in javascript: 这种方式在javascript中迭代json:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM