Ajax, prevent multiple request on click

前端 未结 10 2236
忘掉有多难
忘掉有多难 2020-11-28 04:10

I\'m trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn\'t work. Just the first time works fine, then return fals

10条回答
  •  独厮守ぢ
    2020-11-28 04:47

    I found the approach useful. I've implemented it as a general purpose function for jQuery with ES6.

    export default function (button, promise) {
        const $button = $(button);
        const semaphore = 'requestRunning';
    
        if ($button.data(semaphore)) return null;
        $button.data(semaphore, true);
    
        return promise().always(() => {
            $button.data(semaphore, false);
        });
    }
    

    Because $.ajax() returns a promise, you simply pass in the promise and the function takes care of the rest.

    Roughly speaking, here's the usage.

    import preventDoubleClick from './preventdoubleclick';
    
    ...
    
    button.click(() => {
        preventDoubleClick(this, () => $.ajax()
            .done(() => { console.log("success") }));
    });
    

提交回复
热议问题