简体   繁体   English

如何使用JavaScript解决jSON

[英]How to tackle jSON with javascript

Fist off, here's the jSON object I created with PHPs json_encode function 拳头,这是我用PHP json_encode函数创建的jSON对象

{
    "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. 我使用jQuerys $ .getJSON(...)函数请求对象。

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. 假设所有这些都是正确的,我将一生无法弄清楚如何访问json对象中的数据,甚至是非法的任何形式的响应,以指示幕后正在发生任何事情。

My latest attempt was to copy the example from the jQuery docs like this... 我最近的尝试是像这样从jQuery文档复制示例...

$.getJSON(url, callBack);

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

Which generates the following javascript error 哪个会产生以下javascript错误

jquery-1.2.6.min.js (line 19) TypeError: Result of expression 'object' [undefined] is not an object. jquery-1.2.6.min.js(第19行)TypeError:表达式'object'的结果[undefined]不是对象。

Which is a little cryptic. 这有点神秘。 Especially since using this 特别是因为使用这个

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

says [object Object] 说[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. PHP返回的JSON不是数组。 Notice the curly braces, not square braces. 注意花括号,而不是方括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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