Ajax多次发送数据
问题描述:
我为用户的帖子做了一个简单的Ajax投票脚本:+ 1和-1。一切工作正常,但有时由于某种原因,一键发送+3,+6,-2等数据我做了一个Chrome开发工具的截图。可以看出,一次点击被称为PHP脚本多次。 dot.gif - 数据发送时的buzy动画。 Ajax多次发送数据
<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";
答
当用户投票时,应该禁用您的控件。所以只需添加一些阻断标志(变量,饼干等):
$(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;
});
});
答
相反jQuery的单击事件试着写的onclick = “函数名();” href ..
例如, ...
请您提供更多信息,无论此页面是否在同一个容器中加载多次。似乎点击事件已多次注册。 – 2012-07-19 06:55:37
这是旧的PHP PHP-Nuke。有一个模块 - 留言簿。我只是将上面的代码插入到模块的index.php中,以用于每个后期输出。 – Astraport 2012-07-19 07:18:04
当我使用jQuery .live()方法时,我也遇到了这样的问题,有时将它与.die()一起使用会很有用,如果您有这种情况,请查看.die()。 – 2012-07-19 07:40:47