从AJAX回调函数中分离数据


Separating Data From AJAX Callback Function

当我按下一个按钮时,我会执行一个返回数据的ajax帖子。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');  

返回一个json。

data = {
  "check" : 1,
  "otherInfo" : {
  }
}

然后,在客户端进行

data.check检查条件以突出显示按钮

以及data.otherInfo以获取其他附加信息。

您可以在服务器端使用json_encode()将php数组转换为json。

是否返回信息数组?是否返回对象?

{
    "returnCode": 4,
    "returnString" : "No way man",
    "LongData" : "This quick brown fox ignored the lazy dogs."
}