I have a problem with javascript, im calling an ajax method that returns this string:
{
"ObjectResponse": {
"Operation": "OK",
"Response": "SUCCESS",
"Message": "List of AAA Found",
"List": [
{
"keySource": "gat\/images\/images_set\/apple.jpg",
"idSiteKey": "1",
"text": "Apple"
},
{
"keySource": "gat\/images\/images_set\/cat.jpg",
"idSiteKey": "2",
"text": "Cat"
},
{
"keySource": "gat\/images\/images_set\/coffee.jpg",
"idSiteKey": "3",
"text": "Coffee"
},
{
"keySource": "gat\/images\/images_set\/dog.jpg",
"idSiteKey": "4",
"text": "Dog"
},
{
"keySource": "gat\/images\/images_set\/horse.jpg",
"idSiteKey": "5",
"text": "Horse"
},
{
"keySource": "gat\/images\/images_set\/police.jpg",
"idSiteKey": "6",
"text": "Police"
},
{
"keySource": "gat\/images\/images_set\/tree.jpg",
"idSiteKey": "7",
"text": "Tree"
}
]
}
}
I assing the content in this way:
xhr.onreadystatechange = ensureReadiness;
....
responseText = xhr.responseText;
If i try to parse it on javascript with:
response = JSON.parse(responseText);
if I acces a property such response.ObjectResponse.Operation I do get the right content.. but when I try to access the List it allways brakes
and if I try the same String but instead of calling the service I assign the content to a var it works I do can access the List
var myTemporalString ='{"ObjectResponse":{"Operation":"OK","Response":"SUCCESS","Message":"List of Keys Found","List":...';
response.JSON.parse(myTemporalString);
Any suggestion why this could be happening?
I Hate Lazy
49k13 gold badges89 silver badges79 bronze badges
asked Oct 26, 2012 at 20:24
cesaregb
7751 gold badge11 silver badges28 bronze badges
2 Answers 2
You can try this way,
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
try{
var mJsonData = JSON.parse(xhr.responseText);
}catch(err){
console.log(err);
alert(err);
return;
}
for(i=0;i<jsondata.ObjectResponse.List.length;i++){
console.log(jsondata.ObjectResponse.List[i].text);
console.log(jsondata.ObjectResponse.List[i].keySource);
console.log(jsondata.ObjectResponse.List[i]. idSiteKey);
}
}
}
}
answered Oct 26, 2012 at 20:41
Satish Bellapu
7401 gold badge6 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use a loop!
var array = response.ObjectResponse.List;
var len = array.length;
for(i=0; i<len; i++) {
//Use array[i] to access the list
array[i].keySource
array[i].idSiteKey
array[i].text
}
answered Oct 26, 2012 at 20:38
Kirk Backus
4,8764 gold badges34 silver badges52 bronze badges
Comments
lang-js
responseText = xhr.responseText;shoud be done insideensureReadiness. You can only use the response from there..List? What do you mean by "it breaks"?Listis an array of object so you should useList[0]['keySource']to get the first object andList[1]['keySource']for the second and so on.