I have a proxy script that outputs json data via php, and I want to be able to manipulate this data using javascript. I have the following code, but it only gets the entire json string outputted by the php script. How do I take the data and be able to access the individual objects with in this json data?
var xmlhttp;
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
loadXMLDoc("http://xxxxx.appspot.com/userbase_us.php?callback=userdata", function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = xmlhttp.responseText;
alert(json);
}
});
asked Jun 8, 2012 at 10:20
Daniel
4,36212 gold badges52 silver badges69 bronze badges
-
possible duplicate of how to parse json in javascriptPolynomial– Polynomial2012年06月08日 10:21:56 +00:00Commented Jun 8, 2012 at 10:21
1 Answer 1
You can use the native JSON.parse method:
var json = JSON.parse(xmlhttp.responseText);
Note that since this is not supported by older browsers, you will most likely want to polyfill it.
answered Jun 8, 2012 at 10:21
James Allardice
166k22 gold badges335 silver badges316 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
James Allardice
@Mr.1.0 - Then your JSON is not valid. Update your question with an example JSON string returned by your script, or use a tool like JSON Lint to validate it.
lang-js