当我按下按钮时,我会执行一个返回数据的ajax post。该 ajax 帖子既更新数据又返回一个数字来告诉我该按钮是否应该突出显示。我的问题是,我希望 ajax post 回调函数返回号码和更新的信息。这在 ajax 文件上很容易做到,但我不确定如何在回调函数上做到这一点。下面是一个简单的示例。
$.post(ajax_file,
{
primary_id: primary_id
},
function (data){
//ajax file calls back the number 1 or the number 0. But I want to return more
//than just that. Maybe an array would work?
if (data == 1)
{
$(the_button).addClass('highlighted');
}
else if (data == 0)
{
$(the_button).removeClass();
}
});
最佳答案
您需要以 JSON 格式做出响应。您的 PHP 代码必须响应一些与此类似的代码 -
$response = array(
'code'=>1,
'updates'=> $updates // this could be HTML or an array.
);
echo json_encode($response);
然后您需要做的就是在 post()
函数中指定您期望的数据为 JSON 格式。
$.post(ajax_file, { primary_id: primary_id }, function (data){
if (data.status == 1) {
$('.the_button').addClass('highlighted');
}
else if (data.status == 0) {
$('.the_button').removeClass();
}
// do something with data.updates
},'json');
关于php - 将数据与 AJAX 回调函数分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310447/