[英]How to read JSONP response data in name and value pairs in Jquery ajax.?
I am trying to read JSON file from other domain with JSONP technique 我正在尝试使用JSONP技术从其他域读取JSON文件
Here is the JSON 这是JSON
callback({
"response":{"docs":[
{
"FirstName":"qwe",
"LastName":"asd",
"Age":"30"},
{
"FirstName":"zxc",
"LastName":"bnm",
"Age":"40"},
.
.
.
{
"FirstName":"poi",
"LastName":"lkj",
"Age":"20"},
]},
})
Here is the Jquery code 这是jQuery代码
$.ajax({
type: "GET",
url: "http://qqq.com/",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (msg) {
$.each(msg.response.docs, function (key, value){
alert(key +"is"+value);
}
});
From the above code i am expecting to get the alert output as 从以上代码中,我希望得到警报输出为
FirstName is qwe
LastName is asd
and so on
But i am getting the alert as 但我得到警报
0 is [object Object]
1 is [object Object]
and so on
can i know what i need to do to get the out put as my expectation like 我能知道我需要做什么才能像我期望的那样得到成功吗
FirstName is qwe
LastName is asd
Thanks in advance 提前致谢
Your $each
function is iterating over the docs
array. 您的$each
函数正在docs
数组上进行迭代。 The parameters passed to it will be: 传递给它的参数将是:
key
: index of doc object key
:doc对象的索引 val
: the doc object itself val
:doc对象本身 Instead, you probably want to also iterate over every (key, value) pair with another loop: 相反,您可能还希望通过另一个循环遍历每个(键,值)对:
success: function (msg) {
$.each(msg.response.docs, function (index, doc){
$.each(doc, function (key, val) {
console.log(key + 'is' + val);
});
}
}
You should first iterate an array and then iterate in single object: 您应该首先迭代一个数组,然后在单个对象中进行迭代:
Something like this: 像这样:
success: function (msg) {
$.each(msg.response.docs, function (singleDoc){
$.each(singleDoc, function (key, value){
alert(key +"is"+value);
}
}
}
when you are using each method of jquery then you get the index as first parameter and in second parameter you get the each object in iterating order. 当您使用jquery的每个方法时,则将索引作为第一个参数,在第二个参数中,将按迭代顺序获取每个对象。
So you need to use code like this 所以你需要使用这样的代码
$.each(msg.response.docs, function (key,value){
console.log('FirstName is '+value.FirstName);
console.log('LastName is'+value.LastName);
.
.
.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.