質問

I have an iteration trough json that I cannot make to work.

$.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. 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.

役に立ちましたか?

解決 2

Use

var data = $.parseJSON(data);

before you start looping to read.

他のヒント

Use .ajax instead of $.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:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top