在AJAX操作后获取php变量?

时间:2011-08-25 17:42:58

标签: ajax

当我点击页面上的按钮时,我会执行以下操作:

$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>", 
data:"vote="+vote,
success: function(){
alert("Vote done");

}

然后,url的页面收到我的POST变量来处理投票:

<?php   
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);

// I get the server timestamp
$timestamp_click=time();

if($timestamp_click-$last_timestamp > $time_limit){ 
   $authorization_vote=false;
}else{
    $authorization_vote=true;
}

我想回来并将$ autorisation_vote发送给AJAX或jQuery,以便提醒用户他的投票是否完成。我听说过回调,但没有成功适应我的情况。怎么样?

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到。

快速而肮脏的方法是在PHP中回显“true”或“false”,如果你这样声明它将在回调函数中可用

$.ajax({
    type: "POST",
    url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>", 
    data:"vote="+vote,
    success: function(data){
       alert(data);
    }

或者您可以设置http标头以返回状态代码,这样您就可以在成功或失败时在ajax调用中声明两个回调

php看起来像这样

<?php   
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);

// I get the server timestamp
$timestamp_click=time();

if($timestamp_click-$last_timestamp > $time_limit){ 
    header("HTTP/1.0 423 Locked"); // The resource that is being accessed is locked
}else{
    header("HTTP/1.0 204 No Content"); // Processed, but not returning content
}

你的ajax调用看起来像这样

$.ajax({
    type: "POST",
    url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>", 
    data:"vote="+vote,
    statusCode: {
       204: function(){ alert("Vote cast"); },
       423: function(){ alert("Vote not cast for whatever reason..."); }
    }

这可能有点矫枉过正,但了解这些事情是件好事。

答案 1 :(得分:0)

$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>", 
data:"vote="+vote,
success: function(data){
   alert(data);
}

(注意添加了data

并在您的php脚本中添加

echo "vote done and some data here";

因为true更改为1而false将为空

所以例子:

if($timestamp_click-$last_timestamp > $time_limit){ 
   $authorization_vote=false;
   echo "voted";
}else{
    $authorization_vote=true;
    echo "vote failed";
}