Prototype believes JSON from PHP is string
I have the following code in JS:
new Ajax.Request('http://www.some_random_url.com',
{
parameters: { start : this.start, stop : this.stop },
method: 'post',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response.posts);
$(response.posts).each( function(item) {
alert(item.title);
}
},
onFailure: function(){ alert('Something went wrong...') }
});
and then I have the following code in PHP. The function takes an array as an argument, and is meant to output JSON.
function view_api($array) {
header('Content-type: application/json');
echo json_encode(array('posts'=>$array));
}
Still, it seems to be treated by prototypejs as a string. When resp开发者_如何学Pythononse
is alerted, everything is fine. But the each loop in JS says response.posts
is undefined.
Do you know why?
If it's returning the JSON as a string then you should parse it first.
var data = JSON.parse(payload);
use evalJSON() to typecast the response in JSON object as
var response = transport.responseText.evalJSON() || "no response text";
set evalJSON: 'force'
in the prototype ajax request options. then use var response = transport.responseJSON
A neat trick with prototype.js is that you can pass the following headers and it will automatically be converted to json.
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');
精彩评论