I am echoing JSON from a php server back to the browser. I am quiet proficient with XML however am new to JSON. Can someone show me how to correctly extract the JSON from the xmlhttpRequest and then pass it into data aka an alert.
My JSON (from PHP server)
{"data": {
"message": "Open the Pod bay doors, Hal",
"type": "request",
"replies" => array(
"id": "12321"
"message": "I'm sorry Dave, I'm afraid I can't do that!"
)
}
}
My request in JS returns the JSON however I have no way of catching it or extracting the inside information… my ajax function is…
function ajax(site){
xmlhttp.open("GET","site",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status!=404) {
var resp =new Function("return "+xmlhttp.responseText)();
}
}
xmlhttp.send(null);
}
Then I am invoking the function in window.onload
window.onload = runJSON()
function runJSON(){
var site = "http://localhost/sites/sandbox/json.php"
ajax(site);
... this is what i am unsure about... how do I access the data in the object
}
alert(data);
}
needs to be
in JavaScript, you can convert JSON to a JS object by running
JSON.parse(str), where you should get yourstrfrom a callback from inside theonreadystatechangehandler:Note:
JSON.parsedoes not exist in older browsers. If you wish to support them too, you will need a library that will shim them in, like jQuery (which will incidentally also take away a lot of pain in AJAX department).