问题
I'm having trouble reading the JSON data from a venues search. Here is my code:
xmlhttpRC = new XMLHttpRequest();
url = "https://api.foursquare.com/v2/venues/explore?ll="+pointStrr+"&oauth_token=V5PI2GJ0KDOVH2GAHNHJ5DVLMRKNF440FR1N1HPG0XHX2OBQ&v=2015643&
callback=JSONP";
xmlhttpRC.open("GET", url, true);
xmlhttpRC.onreadystatechange = recCb;
xmlhttpRC.send(null);
//return recommendedArr;
}
function recCb(data){
//console.log(data);
if(xmlhttpRC.readyState == 4){
if(xmlhttpRC.status == 200){
var recRes = xmlhttpRC.response;
console.log(recRes);
//console.log(recRes);
console.log(recRes.meta.code);
}
}
}
I get the reponse I expect from the server, and firebug shows me that a JSON object is returned, but I am not sure how to access the data inside from here.
console.log(recRes.meta.code) returns the error:
"recRes.meta is undefined"
Where am I going wrong? I want to access the venues information but I am just using meta.code as a simple test. This is probably really simple but I'm stumped!
Thanks in advance, Ross.
回答1:
var decodedResp = JSON.parse(recRes);
if (decodedResp.meta.code === ...)
JSON-object is just a representation of an JS-object, see; it should be parsed first.
回答2:
You need to parse JSON. Modern browsers have JSON.parse built in, older versions of IE etc. do not - you can theoretically use eval(response) but it creates a security hole.
There is a library to parse it if you cannot depend on users having modern browsers.
来源:https://stackoverflow.com/questions/9422372/dealing-with-json-result