-1

我无法使用 jquery 的 get JSON 函数解析 JSOn。请帮忙。这是html代码:

 function getList()
{
$.getJSON("http://localhost/webservice/list.php", function(data){
    for (var i=0, len=data.length; i < len; i++) 
     {
        alert(data[i]);
    }

});

这是设置为 header('Content-type: application/json') 的 list.php 文件

{
"promos":[
{"promo":{"id":"1","name":"MADINAT JUMEIRAH AL QASR","image":"","stars":"","highlights":""}},
{"promo":{"id":"2","name":"MADINAT JUMEIRAH DAR AL MASYAF","image":"","stars":"","highlights":""}},
{"promo":{"id":"3","name":"ATLANTIS THE PALM","image":"","stars":"","highlights":""}},
{"promo":{"id":"4","name":"JUMEIRAH ZABEEL SARAY 5*","image":"","stars":"","highlights":""}},
{"promo":{"id":"5","name":"HABTOOR GRAND BEACH RESORT & SPA","image":"","stars":"","highlights":""}},
{"promo":{"id":"6","name":"HILTON DUBAI JUMEIRAH RESORT","image":"","stars":"","highlights":""}}
]
}

编辑:有人提到我不应该循环数据而不是 data.promos 我试过这个但它没有帮助。我是 JSON 新手:

for (var i=0, len=data.promos.length; i < len; i++) 
     {
        alert(data.promos[i]);
    }
4

3 回答 3

4

data是一个对象,具有一个属性 ( promos),而不是数组。你不能循环过去。(你可以循环data.promos)。

于 2013-07-20T21:05:27.190 回答
1

请注意,您的 JSON-Data 的顶级属性名为promos

<html>
<head>
    <script language="javascript"
            type="text/javascript"
            src="./jquery-1.10.2.min.js" ></script>
</head>
<body>

<script type="text/javascript">

    function getList() {

        $.getJSON( "http://localhost:8888/testbed/jsonProvider.php", function( data ){

            // Use JavaScript's log facility to learn what's inside a variable
            console.log( data );

            var len = data.promos.length;

            for ( var i=0; i < len; i++ ) {

                alert( data.promos[i].promo.id );

            }

        });

    }

    getList();

</script>

</body>
</html>

和这个 PHP 数据提供者jsonProvider.php

<?php
header('Content-type: application/json');
?>
{
"promos":[
{"promo":{"id":"1","name":"MADINAT JUMEIRAH AL QASR","image":"","stars":"","highlights":""}},
{"promo":{"id":"2","name":"MADINAT JUMEIRAH DAR AL MASYAF","image":"","stars":"","highlights":""}},
{"promo":{"id":"3","name":"ATLANTIS THE PALM","image":"","stars":"","highlights":""}},
{"promo":{"id":"4","name":"JUMEIRAH ZABEEL SARAY 5*","image":"","stars":"","highlights":""}},
{"promo":{"id":"5","name":"HABTOOR GRAND BEACH RESORT & SPA","image":"","stars":"","highlights":""}},
{"promo":{"id":"6","name":"HILTON DUBAI JUMEIRAH RESORT","image":"","stars":"","highlights":""}}
]
}
于 2013-07-20T21:43:07.220 回答
-1

尝试这个 :

$.each(data.promo, function(key, value) {
        console.log(value.id);
        //and so on...
});
于 2013-07-20T21:18:28.177 回答