2010-09-04 79 views
5

即時通訊使用Ajax值發送到一個PHP腳本寫一些值到數據庫:阿賈克斯後返回值

$.ajax({ 
    type: "POST", 
    data: "action=vote_down&id="+$(this).attr("id"), 
    url: "vote.php", 
    success: function(msg) { 
     $("span#votes_count"+the_id).fadeOut(); 
     $("span#votes_count"+the_id).html(msg); 
     $("span#votes_count"+the_id).fadeIn();      
    } 
}); 

正如你可能會從action=vote_down告訴腳本是一個投票腳本。

我已經阻止用戶投票不止一次,通過登錄投票反對那裏的用戶名和ID在vote.php,如果有用戶名和ID已經在數據庫對同一篇文章,然後我不添加投票數據庫。

我個人認爲查詢每個頁面加載的數據庫以檢查用戶是否已經投了票可能相當密集,有很多地方可以在單個頁面上進行投票。

所以相反,我會向用戶顯示投票選項,但是當他們投票時,我想要一些如何從vote.php返回一個值,說他們已經投了票。

有關最佳方法的任何想法?

回答

2

使用JSON

如果這是你的文件顯示錶決方式:

<div id='voteform-div'> 
<form id='voteform'> 
    Your form elements and a submit button here. 
</form> 
</div> 

你的JS代碼如下所示:

jQuery('#voteform').live('submit',function(event) { 
    $.ajax({ 
     url: 'vote.php', 
     type: 'POST', 
     data: "action=vote_down&id="+$(this).attr("id"), 
     dataType: 'json', 
     success: function(messages) { 
      for(var id in messages) { 
       jQuery('#' + id).html(messages[id]); 
      } 
     } 
    }); 
    return false; 
}); 

vote.php應像這樣:

// Get data from $_POST array. 

if(Already voted) { 

    // It will replace the id='voteform-div' DIV with error message 
    $arr = array ("voteform-div" => "you have already voted."); 

} else { 

// Store vote in database 

    // It will replace the id='voteform-div' DIV with confirmation message 
    $arr = array ("voteform-div" => "Yor vote is submitted. Thanks"); 

} 

echo json_encode($arr); // encode array to json format 



有關這方面的更多細節this question