0

当我按下一个按钮时,我执行一个返回数据的 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();
          }         
});  
4

3 回答 3

3

您需要以 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');  
于 2012-09-07T01:10:10.460 回答
0

而是返回一个 json。

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

然后,在客户端,做

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

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

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

于 2012-09-07T01:11:18.090 回答
-1

返回一组信息?返回一个对象?

{
    "returnCode": 4,
    "returnString" : "No way man",
    "LongData" : "This quick brown fox ignored the lazy dogs."
}
于 2012-09-07T01:09:54.423 回答