问题描述:

I am unable to parse JSOn with jquery's get JSON function. Please help. Here is the html code:

 function getList()

{

$.getJSON("http://localhost/webservice/list.php", function(data){

for (var i=0, len=data.length; i < len; i++)

{

alert(data[i]);

}

});

And here is the list.php file which is set to 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":""}}

]

}

Edit: Someone mentioned that I should not loop over data rather than data.promos I tried this but it doesn't help. I am new to JSON:

for (var i=0, len=data.promos.length; i < len; i++)

{

alert(data.promos[i]);

}

网友答案:

Try this :

$.each(data.promo, function(key, value) {
        console.log(value.id);
        //and so on...
});
网友答案:

data is an object, with one property (promos), not an array. You can't loop over it. (You can loop over data.promos).

网友答案:

Note, that the top-level property of your JSON-Data is named 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>

and this PHP data provider 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":""}}
]
}
相关阅读:
Top