如何避免Ajax按钮被点击两次

4

我正在尝试使用 ajax 调用向数据库中插入数据

我的问题是,当我点击按钮两次时,数据会存储两次

这让我很烦恼。我该如何避免这种情况发生?

<from><button id ="GdStartTest"> </button></form>
$("#GdStartTest").click(function(){
$.ajax({
    url: "gdcontroller.php",
    method: "POST",

还有这个控制器:

$studentQuery = $conn->query("INSERT INTO r_job_scores 

$("#GdStartTest").click(function(e){e.stopPropagation();... rest of the code - Alive to die - Anant
可能是仅绑定一次事件的重复问题。 - Alive to die - Anant
Lol关于“让我生病”的评论 - Mulan
3个回答

8

在单击按钮后立即禁用它,并在ajax完成回调函数中启用它。

$("#GdStartTest").click(function(){

    // cache the button reference
    var $this = $(this);

    // disable the button
    $this.prop('disabled', true);

    $.ajax({
        url: "gdcontroller.php",
        method: "POST",
        .........
        complete : function(){
          // enable the button
          $this.prop('disabled', false);
       },
 ......

或者使用one()方法仅执行一次事件处理程序。
$("#GdStartTest").one('click', function(){
    $.ajax({
        url: "gdcontroller.php",

2
我宁愿将它放在“complete”回调函数中,这样无论ajax调用如何结束,它都会被执行。 - Mike
@Mike:是的,那是一个完美的方法...我会更新答案...谢谢m:) - Pranav C Balan
我不明白为什么,但是顶部的"disable"方法对我无效,我总是可以使用2-3次点击。而"one()"方法对我来说是100%有效的。 - Scott

2

有很多选项可以实现这个功能,比如禁用按钮,将事件监听器设置为关闭:

$("#GdStartTest").click(function(){
    $(this).prop('disabled', true);
});

$("#GdStartTest").click(function(){
    $("#GdStartTest").off();
});

2
  1. Disable the button.
  2. Use a Loader on ajax using beforeSend as another parameter.

       $.ajax({
               beforeSend: function(){
                   $(".loader").show();
               }
       });
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接