5
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

ajaxの連打防止

コード

いろいろ調べたけど、
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);// ← ここ
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?