Ajax多次发送数据

时间:2012-07-19 06:39:03

标签: php jquery ajax voting

我为用户的帖子制作了一个简单的Ajax投票脚本:+ 1和-1。一切正常,但有时只需点击一下就可以发送数据+ 3,+ 6,-2等等。我制作了Chrome开发者工具的截图。可以看出,一次点击多次称为PHP脚本。 dot.gif - 数据发送时的buzy动画。enter image description here

<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";

2 个答案:

答案 0 :(得分:1)

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

$(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;
});
});

答案 1 :(得分:-1)

而不是jquery click事件尝试写onclick =“function_name();”为了一个href ..

例如...