Ajax多次发送数据

问题描述:

我为用户的帖子做了一个简单的Ajax投票脚本:+ 1和-1。一切工作正常,但有时由于某种原因,一键发送+3,+6,-2等数据我做了一个Chrome开发工具的截图。可以看出,一次点击被称为PHP脚本多次。 dot.gif - 数据发送时的buzy动画。 enter image description hereAjax多次发送数据

<script type="text/javascript" src="raitings/jquery.js"></script> 
<script type="text/javascript">$(function() {$(".vote").click(function() { 

var id = $(this).attr("id"); 
var name = $(this).attr("name"); 
var dataString = 'id='+ id ; 
var parent = $(this); 

if(name=='down') 
{ 
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">'); 
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html) 
    { parent.html(html);} 
}); 
} 
else 
{ 
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">'); 
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html) 
    { parent.html(html); 
    } }); 
} 
return false; 
    }); 
}); 
</script> 

<?php 
echo "<div class=\"box1\"><div class=\"up\"><a href=\"#\" class=\"vote\" title=\"+ 1\" alt=\"+ 1\" id=".$row["id"]." name=\"up\">".$up."</a></div>" 
."<div class=\"down\"><a href=\"#\" class=\"vote\" title=\"- 1\" alt=\"- 1\" id=".$row["id"]." name=\"down\">".$down."</a></div></div>\n"; 
+0

请您提供更多信息,无论此页面是否在同一个容器中加载多次。似乎点击事件已多次注册。 – 2012-07-19 06:55:37

+0

这是旧的PHP PHP-Nuke。有一个模块 - 留言簿。我只是将上面的代码插入到模块的index.php中,以用于每个后期输出。 – Astraport 2012-07-19 07:18:04

+1

当我使用jQuery .live()方法时,我也遇到了这样的问题,有时将它与.die()一起使用会很有用,如果您有这种情况,请查看.die()。 – 2012-07-19 07:40:47

当用户投票时,应该禁用您的控件。所以只需添加一些阻断标志(变量,饼干等):

$(function() { 
var isUserVoted = false; 
$(".vote").click(function() { 
    if (isUserVoted) { 
     return false; 
    } 

    isUserVoted = true; 
    var id = $(this).attr("id"); 
    var name = $(this).attr("name"); 
    var dataString = 'id='+ id ; 
    var parent = $(this); 

    if(name=='down') { 
     $(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">'); 
     $.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html) 
    { parent.html(html);} 
     }); 
    } else { 
     $(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">'); 
     $.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html) { parent.html(html); 
    } }); 
    } 
    return false; 
}); 
}); 
+0

谢谢。我尝试过,但仍然要发送多个数据。 – Astraport 2012-07-19 09:02:33

+0

重点在于让用户有机会在同一页面的多个帖子中进行投票,而在您的代码中这是不可能的。 – Astraport 2012-07-19 09:20:01

+0

只需为所有投票创建标志(某些地图等)。如果用户已投票,则不应将任何数据发送到服务器。同样按类名搜索DOM元素是最慢的。 – Serjio 2012-07-19 10:04:28

相反jQuery的单击事件试着写的onclick = “函数名();” href ..

例如, ...