简体   繁体   中英

Only one ajax call, wait until success until next click

如何防止用户在运行ajax调用的链接上单击很多次后才成功运行

if you mean what I think you mean, then as soon as the button is clicked you'd disable the button in your ajax function (before you get to the actual making of an http request). Then once your ajax call is complete your onreadystate function would re-enable it.

to disable a button, if it has an id.

document.getElementById("theidofthebutton").enabled = false;

to re enable it...

document.getElementById("theidofthebutton").enabled = true;

Edit: I see you're refering to a link not a button. I could be wrong but I think you can still disable in the same way.

One simple solution is to add a class to the link when the user clicks, and remove the class when the response is received.

Each click of the link checks to see if the pending class exists, and only sends the AJAX request if not.

Then the complete: callback removes the pending class.

$('a.myLink').click(function() {
    var $th = $(this);
    if( !$th.hasClass('pending') ) {
        $th.addClass('pending');
        $.ajax({
          url:'something',
          complete: function() {
              $th.removeClass('pending');
          }
        });
     }
});

Try using the jquery plugin BlockUI to block the user from clicking the link again. This can be done at the Element or Page level.

// unblock when ajax activity stops 
$(document).ajaxStop($.unblockUI); 

function test() { 
    $.ajax({ url: 'wait.php', cache: false }); 
} 

$(document).ready(function() { 
    $('#pageDemo2').click(function() { 
        $('div.test').block({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' }); 
        test(); 
    });  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM