如何从php文件中收到的JSON中检索对象?

时间:2014-07-16 09:52:42

标签: javascript php json

我的服务器上有一个places.php文件,它返回以下json:

{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}

在我的javascript中,我使用以下代码:

$(document).ready(function() {
   var url="places.php";
   $.getJSON(url,function(data){
       $.each(data.places, function(i,place){
          var new1 = place.poi_id;
          alert(new1);
       });
   });              
});

但是没有弹出带有poi_id的消息框。我做错了什么?

4 个答案:

答案 0 :(得分:1)

这样怎么样。

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">

// data source
var jsonStr = '{"places":[{"poi_id":"1","poi_latitude":"53.9606","poi_longitude":"27.6103","poi_title":"Shop1","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 1, 1","poi_phone":null,"poi_website":null},{"poi_id":"2","poi_latitude":"53.9644","poi_longitude":"27.6228","poi_title":"Shop2","poi_category":"Shopping","poi_subcategory":"Grocery Store","poi_address":"Street 2","poi_phone":null,"poi_website":null}]}';

// parse json string to object
var jsonObj = JSON.parse(jsonStr);

// usage 1
console.log('iterate - without jQuery');
for (var i = 0; i < jsonObj.places.length; i++)
{
    var place = jsonObj.places[i];
    console.log(place.poi_id);
}

// usage 2
console.log('iterate - with jQuery');
$(jsonObj.places).each(function(index, place)
{
    console.log(place.poi_id);
});

</script>

输出:

enter image description here


如何在代码中使用它:

$(document).ready(function()
{
    $.getJSON("/path/to/places.php", function(data)
    {
        // data here will be already decoded into json object, 
        // so... you do this
        $(data.places).each(function(index, place)
        {
            console.log(place.poi_id);
        });
    });             
});

另请参阅手册:http://api.jquery.com/jquery.getjson/

应该有效,如果没有留下错误或原因的评论。

答案 1 :(得分:0)

这会让你更接近:

for (var property in data) 
{
    if (data.hasOwnProperty(property)) 
    {
        console.log(property);
    }
}

答案 2 :(得分:0)

你的php实际上是在生成JSON吗?如果它只获取特定文件,则使用JS和AJAX选择文件可能更容易。这里是我用于php的代码。

function callPHP(dataToSend)
{
    $.post( "places.php", dataToSend )
        .done(function( phpReturn ) {
            console.log( phpReturn );
            var data = JSON.parse(phpReturn);
            for(var i = 0;i<data.places.length;i++)
                console.log(data.places[i].poi_id);
    });}
}

答案 3 :(得分:0)

将places.php文件编码设置为UTF-8解决了问题

相关问题