Sending JSON from PHP to JavaScript with AJAX
I am banging my head against the wall here, and I am hoping someone can help me out.
I have an AJAX function which calls a PHP page. That page returns a JSON object, which should then be parsed and displayed to the user. Everything works fine except when the JSON object is returned, trying to parse it gives undefined.
The PHP:
$jsonArray= array(开发者_如何学JAVA
'request' => 'this is the request',
'response' => 'this is the response'
);
echo json_encode($jsonArray);
On the Ajax side, I do the following:
var display=xmlHttp.responseText;
alert(display); //gives {"request":"this is the request","response":"This is the response"}
alert(display.request); //gives undefined
Am I missing something obvious? Pasting the same string directly into a JavaScript variable seems to work fine...
You will need to parse the json string. JSON.parse should do the tricks. If it's not working, there's probably a problème with the object you encoded.
You need to parse the JSON data returned from your server. There are many libraries to do this such as:
jQuery,
var myObject = eval('(' + display + ')');
display
is a string. you will need to use
var obj = eval(display)
but eval() is not as safe as using JSON.parse().
精彩评论