简体   繁体   中英

How to tackle jSON with javascript

Fist off, here's the jSON object I created with PHPs json_encode function

{
    "Gatwick":[
        {
            "destination":"VCE",
            "destination_name":"Venezia Marco Polo"
        },{
            "destination":"VCE",
            "destination_name":"Venezia Marco Polo"
        },{
            "destination":"VCE",
            "destination_name":"Venezia Marco Polo"
        }
    ],
    "Heathrow":[
        {
            "destination":"VCE",
            "destination_name":"Venezia Marco Polo"
        },{
            "destination":"VCE",
            "destination_name":"Venezia Marco Polo"
        }
    ]
}

Which I think is ok as I understand it. I requested the object using jQuerys $.getJSON(...) function.

Assuming all of that is correct, I can't for the life of me figure out how to access the data in the json object or even illicit any kind of response to indicate anything is happening under the hood.

My latest attempt was to copy the example from the jQuery docs like this...

$.getJSON(url, callBack);

function callBack(data){
    $.each(data.items, function(i, item){
        alert("YO");
    });
}

Which generates the following javascript error

jquery-1.2.6.min.js (line 19) TypeError: Result of expression 'object' [undefined] is not an object.

Which is a little cryptic. Especially since using this

function callBack(data){ alert(data); }

says [object Object]

but this

function callBack(data){ alert(data[0]); }

gives me nothing.

Where am I going wrong here?

jQuery示例中的“ .items”是一个.NET东西-您有数据data.Gatwick[0].destination == 'VCE'

you don't have 'items' in your data object... just use

$.each(data, function(i, item){

at which point you can do:

item[0].destination

The JSON that the PHP is returning is not an array. Notice the curly braces, not square braces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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