问题描述
我有一个ajax调用,该调用返回JSON数据(已附加数据).将数据转换为String之后,它是这样的:
I have an ajax call that returns JSON data (Data Attached).After converting the data into String, this is how it looks like:
{
"shipments":[
{
"companyName":"TriStar Inc.",
"shipmentDate":null,
"transMode":"NDAY",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"DAISY N.",
"customerZip":"90544"
},
"orderStatus":true
},
{
"companyName":"Carbo Box",
"shipmentDate":null,
"transMode":"COUR",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"TOM K",
"customerZip":"07410"
},
"orderStatus":true
}
]
}
现在,当我在Firefox中打印JSON响应时,它看起来像:
Now when I print the JSON response in Firefox, it looks like:
[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]
我的问题是,如何从此响应中提取companyName和customerName字段.以下无效:
My question is, how do I extract companyName and customerName field out of this response. The following isnt working:
load: function(response){
for(var i in response){
console.log(response.shipments[i].companyName);
}
推荐答案
如果获取的是json字符串,则需要先对其进行解析.
if you get a string that is json, you need to parse it first.
var obj = JSON.parse(jsonString);
现在您有了正确的对象文字,并且可以正常访问
now you have a proper object literal, and you can access it normally
var shipments = obj.shipments;
shipments
现在是一个javascript数组...
shipments
is now a javascript array...
for(var i = 0; i < shipments.length; i++){
console.log(shipments[i].companyName);
}
请注意,您不应在数组上使用for(var i in x)
构造.
note you should not use the for(var i in x)
construct on arrays.
这篇关于从Ajax响应中提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!