LoginSignup
5
5

More than 5 years have passed since last update.

ajaxの連打防止

Last updated at Posted at 2015-10-13

コード

いろいろ調べたけど、
abortの利用方法がうまくいかないから、
それをflagで送信中かどうか判定して
連打を防止する

$(function(){
    var flag;
    $('#execute').click(function(){
        if (flag) {
            return;
        }
        flag = true;//flagを立てる
        $.ajax({
            url: "hoge.com",
            type: "post",
            data:{
              foo: foo,
            }
        })
        .done(function(data) {
            // ...
        })
        .fail(function(data) {
            // ...
        })
        .always(function(data) {
            flag = false;//通信した後、flag解除する
        })
    });
});

setTimeoutで連打送信の制約

改修版
setTimeoutで処理を一旦停止させる

var flag = 0;
function hoge() {
    if(flag) return false;

    $.ajax({
        url: url,
        type: 'POST',
        data: { 
                   foo: foo,
        },
    })
    .done( function(data) {
                //...
    })
    .fail( function(XMLHttpRequest, textStatus, errorThrown) {
        //...
    })
    flag = 1;
    setTimeout(function(){ flag = 0;}, 500);// ← ここ
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5