如何避免,Ajax按钮单击两次

时间:2017-01-09 07:23:00

标签: javascript php jquery ajax button

我正在尝试使用ajax调用

将数据插入数据库
  

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

它让我生病了。我怎么能避免它?

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

这个控制器:

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

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:2)

  1. 禁用按钮。
  2. 使用beforeSend作为另一个参数在ajax上使用Loader。

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