用JavaScript解析jQuery数据(JSON)

时间:2022-12-01 13:06:28

I am using PHP, jQuery, and JSON. Now I need to know how to parse the jQuery data in JavaScript.

我正在使用PHP,jQuery和JSON。现在我需要知道如何在JavaScript中解析jQuery数据。

load.php

<?php

    ...
    $json =json_encode($array);

?>

It returns jQuery by the following data.

它通过以下数据返回jQuery。

 [{"name":"STA","distance":"250","code":25},
 {"name":"GIS","distance":"500","code":45}]

jQuery code

$.getJSON("load.php", function(json){
    // Access object
    var a = json;
    pass(a);
});

Now I need to pass the JSON (a) to JavaScript defined in file my.js:

现在我需要将JSON(a)传递给文件my.js中定义的JavaScript:

var myjson = {};

function pass(a) {
    myjson = a;

    //Here, how do I get name, and distance, code.
    //I have tried "alert(myjson.name)". It returns undefined.
}

What changes should I make to my logic?

我应该对我的逻辑做出哪些改变?

2 个解决方案

#1


You have an array of JSON objects, so you need to loop through the array to get each individual object:

您有一个JSON对象数组,因此您需要遍历数组以获取每个单独的对象:

for(var x = 0; x < myjson.length; x++) {
    alert(myjson[x].name);
    // myjson[x].distance, myjson[x].code also available
}

Or, if you want to do it the jQuery way:

或者,如果你想以jQuery的方式做到这一点:

jQuery.each(myjson, function(x) {
    alert(myjson[x].name);
});

Both examples will give you an alert with 'STA' followed by 'GIS'.

这两个示例都会为您提供“STA”后跟“GIS”的警报。

In addition to this, as pointed out by OIS, you're trying to read the wrong variable in your code. The JSON should be in variable named a.

除此之外,正如OIS所指出的,您正试图在代码中读取错误的变量。 JSON应该在名为a的变量中。

#2


You try to use a variable named json which is not defined in the scope of your function. Instead you have to use the argument named a.

您尝试使用名为json的变量,该变量未在函数范围内定义。相反,你必须使用名为a的参数。

function pass(a) {
   var i;
    while(i = a.pop()) {
        alert(i.name + " " + i.distance);
    }
}

#1


You have an array of JSON objects, so you need to loop through the array to get each individual object:

您有一个JSON对象数组,因此您需要遍历数组以获取每个单独的对象:

for(var x = 0; x < myjson.length; x++) {
    alert(myjson[x].name);
    // myjson[x].distance, myjson[x].code also available
}

Or, if you want to do it the jQuery way:

或者,如果你想以jQuery的方式做到这一点:

jQuery.each(myjson, function(x) {
    alert(myjson[x].name);
});

Both examples will give you an alert with 'STA' followed by 'GIS'.

这两个示例都会为您提供“STA”后跟“GIS”的警报。

In addition to this, as pointed out by OIS, you're trying to read the wrong variable in your code. The JSON should be in variable named a.

除此之外,正如OIS所指出的,您正试图在代码中读取错误的变量。 JSON应该在名为a的变量中。

#2


You try to use a variable named json which is not defined in the scope of your function. Instead you have to use the argument named a.

您尝试使用名为json的变量,该变量未在函数范围内定义。相反,你必须使用名为a的参数。

function pass(a) {
   var i;
    while(i = a.pop()) {
        alert(i.name + " " + i.distance);
    }
}