Reputation: 451
I am trying to read JSON file from other domain with JSONP technique
Here is the 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
$.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
Upvotes: 0
Views: 1662
Reputation: 1096
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.
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);
.
.
.
});
Upvotes: 0
Reputation: 166
Your $each
function is iterating over the docs
array. The parameters passed to it will be:
key
: index of doc objectval
: the doc object itselfInstead, 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);
});
}
}
Upvotes: 3
Reputation: 3062
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);
}
}
}
Upvotes: 0