无法解析json响应,它实际上不是空的但是返回undefined

时间:2015-07-09 12:15:39

标签: javascript jquery json

我有这个json代码,我用它来发送一个帖子请求并检索数据,然后解析它(参见下文)。

$.ajax({
       url: '/test',
       type: 'post',
       data: { id : "1"},
       dataType: 'json',
       success: function(response){
           if(response.success){
               console.log(JSON.stringify(response.disputeRecord));
                $.each(response.disputeRecord, function(index, value){
                   alert(value.creation_date);

                });
           }
       }
    });

这是" response.disputeRecord"的json内容。 (来自控制台的视图)

{"no":7,"employee_id":"MMMFLB003","creation_date":"2015-07-09","log_date":"2015-06-25","log_type":"LOGGED","dispute_time":"07:00","reason":"No Logout data","effect":"Update Logout Data","status":"HR APPROVED","authorized_person":"MMMFLB003","authorized_reason":"You have it","mngmt_updated_at":"2015-07-09 03:12:12","hr_approver":"MMMFLB003","hr_approver_reason":"Approve Dispute Request","hr_updated_at":"2015-07-09 03:13:01"}

正如你所看到的,我试图警告" creation_date"这实际上存在于json响应中,但它给了我" undefined",任何想法,线索?

3 个答案:

答案 0 :(得分:2)

上面的示例显示您没有获得disputeRecord的数组 - 只有一个。在这种情况下,each()会使问题混乱,因为无法解析。试试这个......

$.ajax({
   url: '/test',
   type: 'post',
   data: { id : "1"},
   dataType: 'json',
   success: function(response){
       if(response.success){
           console.log(JSON.stringify(response.disputeRecord));
           console.log(response.disputeRecord.creation_date);
       }
   }
});

答案 1 :(得分:0)

您在对象上使用$.each,而不是数组。 index参数实际上是您对象的属性名称,value将是相应的属性值。您将获得("no", 7)("employee_id", "MMMFLB003")等等。

答案 2 :(得分:0)

更改为:

$.each(response.disputeRecord, function(index, value){
    if (index == "creation_date")
        alert(value);
});

index是属性名称,value是属性值,因此您需要检查哪个属性,然后提醒其值。

http://jsfiddle.net/44z83jpn/

或者直接从对象中直接访问属性并删除$ .each:

if(response.success){
    alert(response.disputeRecord.creation_date)
}    

http://jsfiddle.net/j0vL9f05/