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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog