PHP echo json_encode to jQuery not working?
I was developing a site on my computer and was able to get AJAX requests with jQuery working fairly painlessly. On the production server, however, I'm running into problems.
This is how the CodeIgniter controller I have returns a result:
# Return that everything worked.
$return = array('result' => 'success', 'data' => $item);
echo json_encode($return);
And this is some sample jQuery code:
$.post("../../../list/vote/", { 'item_id' : item_id, 'value' : 0, 'action' : 'delete' },
function(data) {
if(data.result || !data.result) {
if(votes == null) votes = 0;
$(button).children('strong').text(--votes);
$(button).attr('name', '').removeClass('vote_cast');
$(button).parent('.meta').attr('name', '');
}
}, "json");
The problem is that PHP is returning a 200 OK status but no response is shown in Firebug. Since nothing is being returned, jQuery is saying data is null.
开发者_如何学GoI'm using MAMP locally (PHP/5.3.5) and PHP/5.3.2-1ubuntu4.9 on the server. It works locally but not on the server. What could be wrong?
EDIT: Some more info. This is happening for every AJAX request on my site in the production server. The request actually goes through (votes are cast, items are added, etc...), it's just that jQuery isn't informed of the result (which explains why data is null).
UPDATE: Scott Harwell figured it out. After I echo'd the json_encode, PHP continued trying to process the rest of the code. It was fixed by adding exit();
after each echo json_encode();
.
Looks like you are accessing the vote page with relative paths. Have you tried explicitly writing the path or give a proper url instead of ../../../list/vote?
精彩评论