【问题标题】:How to Avoid, Ajax button click twice如何避免,Ajax 按钮点击两次
【发布时间】:2017-05-23 09:52:52
【问题描述】:

我正在尝试使用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
  • bind event only once的可能重复
  • 大声笑:“让我恶心”

标签: javascript php jquery ajax button


【解决方案1】:

点击按钮后立即禁用它,并在 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",

【讨论】:

  • 我宁愿把它放在“完成”回调中,这样无论 ajax 调用如何结束,它都会被执行。
  • @Mike :是的,这是一个完美的方式......我会更新答案......谢谢m :)
【解决方案2】:

有很多选项可以实现这一点,禁用按钮,关闭事件监听器:

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

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

【讨论】:

    【解决方案3】:
    1. 禁用该按钮。
    2. 在 ajax 上使用加载器,使用 beforeSend 作为另一个参数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-08
      • 2017-06-06
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 2020-06-30
      相关资源
      最近更新 更多