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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大