问题
My problem is somewhat similar to cakephp, jquery, .ajax(), dataType: json, but my observations are little different.
I am working on a Cake PHP project. Consider a group_assoc
submodule of opstools
module. So, there is this function group_assoc()
inside opstools_controller.php
which is invoked by an ajax call to update group associations.
My ajax post is like this -
$.post( url,
function(data)
{
if(data)
{
alert(data.success); //alerts -> undefined
alert(data); //alerts -> {"success":true} or {"success":false}
if(data.success)
{
//does not work
}
}
}, "json");
And inside the opstools_controller.php
I have -
function group_assoc()
{
...
...
//some code
...
...
$success //contains true or false - depending on previous logic
echo json_encode(array("success" => $success));
}
So, inside the Ajax response handler function (in the ajax posting part), I am getting a string like {"success":false}
.
How do I fix this problem. I remember using similar Ajax posting and responding using json_encode, which worked perfectly fine in a previous project with Core PHP (no Cake PHP). What could be the problem here? Any pointers?
Update
Do I need to explicitly set any header? Why would that be needed? Where to check if it is set that we are returning text. I tried putting header("HTTP/1.1 200 OK");
before the echoing part, as is done in the existing code - similar Ajax handler functions.
Also, I have set $this->autoRender = false;
in my module.
回答1:
It looks to me like you might be missing an argument to the $.post()
API:
.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
Specifically, the data
argument. The API's example seems to indicate that it's smart enough to figure out when it's missing (the argument doesn't appear in the API example), but it may be worth adding it explicitly:
$.post( url, null,
function(data)
{
if(data)
{
alert(data.success); //alerts -> undefined
alert(data); //alerts -> {"success":true} or {"success":false}
if(data.success)
{
//does not work
}
}
}, "json");
回答2:
Make sure you're sending the correct header type
header('Content-type: application/json');
Alternatively you can use jQuery's getJSON() method to handle JSON
来源:https://stackoverflow.com/questions/6464248/unable-to-properly-read-json-encoded-success-failure-statuses-sent-by-cake-php-c