在JavaScript(JSON)中解析jQuery数据 [英] Parsing jQuery data in JavaScript (JSON)

查看:74
本文介绍了在JavaScript(JSON)中解析jQuery数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<?php

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

?>

它通过以下数据返回jQuery.

It returns jQuery by the following data.

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

jQuery代码

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

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

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

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?

推荐答案

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

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

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

或者,如果您想使用jQuery方式:

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

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

两个示例都将向您发出"STA"后跟"GIS"的警报.

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

此外,正如OIS指出的那样,您正在尝试读取代码中的错误变量. JSON应位于名为a的变量中.

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.

这篇关于在JavaScript(JSON)中解析jQuery数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆