dtcd27183 2017-02-13 17:29
浏览 86
已采纳

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

I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.

$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

$.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

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?

  • 写回答

3条回答 默认 最新

  • doubai9014 2017-02-13 17:36
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?