简体   繁体   English

使用jquery解析JSON响应中的项目

[英]Using jquery to parse items from a JSON response

I am using PHP and Ajax to parse some JSON. 我正在使用PHP和Ajax解析一些JSON。 The PHP is creating the array like this. PHP正在创建这样的数组。

$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;

I use the following jquery code 我用下面的jQuery代码

$.ajax({
        type: "POST",
        dataType: "json",
        url: "msstatup.php",
        data: data
    }).done(function(msg) {
    var response = jQuery.parseJSON(JSON.stringify(msg));
    console.log(response);
    pid = response[0].pid;
    console.log('id = ' + pid);
    });

I can see the output from the first console.log as 我可以看到第一个console.log的输出为

Object {pid: "p1", comp: 20, colour: "red"}

However I cannot extract the individual variables, it gives the message 但是我无法提取单个变量,它给出了消息

Uncaught TypeError: Cannot read property 'pid' 

How can I extract the variable? 如何提取变量?

You've made this more complicated than it needs to be. 您已经使它变得比所需复杂。 msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON . msg已经是一个对象,然后您可以将其转换为字符串,然后使用stringifyparseJSON返回对象。 And then you try to use it like an array, when it is an object. 然后,当它是一个对象时,尝试像数组一样使用它。

Try this: 尝试这个:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "msstatup.php",
    data: data
}).done(function(msg) {
    var pid = msg.pid;
    console.log('id = ' + pid);
});

You are returning an object, not an array. 您正在返回一个对象,而不是数组。

Also it makes no sense to stringify the data object and parse that string back to object again 同样,对数据对象进行字符串化并再次将该字符串解析回对象也没有意义。

Try 尝试

var pid = msg.pid;
console.log('id = ' + pid);

First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response. 首先,无法想象为什么先进行字符串化然后解析JSON响应是必要的。

Second, you are trying to access response[0] as if it were an array, which it isn't. 其次,您尝试访问response[0]就像它是一个数组一样,不是。 You can simply use 您可以简单地使用

response.pid;

To access the object key. 访问对象密钥。

As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to 由于您无需先进行字符串分类再解析响应,因此您可以直接访问msg ,因此一切都归结为

$.ajax({
    type: "POST",
    dataType: "json",
    url: "msstatup.php",
    data: data
}).done(function(msg) {
    console.log(msg.pid);
});

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

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