2016-08-18 84 views
2

我想在HTML中显示响应对象的特定值。但我无法显示这些值。在php/js中读取JSON响应对象

With json.stringify(data)我可以将响应转换为字符串。我想向用户显示Status和StatusCode。我如何获得这些值?

demo

<script> 
$jq.ajax({ 
    url: 'api url', 
    type: 'GET', 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'jsonp', 
    success: function(data) { 
     var JSONString =JSON.stringify(data); 

     //var json = $jq.parseJSON(data); 
     $jq.each(data.ShipmentData, function(index, value){ 
      // alert(JSON.stringify(value)); 
      //console.log(value); 
      //console.log(JSON.stringify(Shipment)); 
     }); 

    }, 
    error: function() { 
     alert("FAIL"); 
    } 
}); 
<script> 

回答

2

无需字符串化您的数据!

您只需访问对象属性。就像这样:

$jq.each(data.ShipmentData, function(){ 
    console.log(this.Shipment.Status.Status); 
    console.log(this.Shipment.Status.StatusCode); 
}); 

其中this是每次迭代

+0

thanks..it works。 – nilesh

-2

尝试,如果你想在每个循环中使用对象来使用JSON.parse来代替JSON.stringify的当前对象。

var obj = jq.parseJSON(data); 
for(var i= 0; i < obj.length; i++){ 
    console.log(obj[i]); 
} 
+0

thnx for d reply。但它不会工作。它throws/SyntaxError:JSON.parse:在JSON数据的第1行第2列的意外字符/ – nilesh