php - Ajax post 返回值

标签 php ajax

我正在使用 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 中看出的那样,该脚本用于投票脚本。

我已经通过在 vote.php 中登录用户名和 ID 来防止用户多次投票,如果用户名和 ID 已经在数据库中反对同一个帖子,那么我不要将投票添加到数据库。

我个人认为在每个页面加载时查询数据库以检查用户是否已经投票可能会非常密集,在一个页面上有很多地方可以投票。

因此,我将向用户显示投票选项,但当他们投票时,我想知道如何从 vote.php 返回一个值,表示他们已经投票。

关于最佳方法的任何想法?

最佳答案

使用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 .

关于php - Ajax post 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3640553/

相关文章:

php - 在多维数组中查找最小值并返回键

javascript - jQuery - 异步 Ajax 请求?

php - 用 php 和 ajax 更新 mysql 表

java - JSP 使用过滤器写入响应

javascript - 在以下情况下如何使用 AJAX 实现删除功能?

php - 如何查找给定句子中存在的列值? mysql

php - 着陆页重定向跟踪 - Google

php - 插入批处理数据数组?

带有 Struts 1.x 版本的 AJAX

javascript - Bootstrap 表单验证 - 使用单击事件验证表单