jQuery Ajax SyncLock

99封情书 提交于 2019-12-24 01:13:32

问题


I have a couple of buttons that users can click to load content with jQuery's $.ajax. All the buttons load the content into the same div tag. The problem is that if users click multiple times quickly, the content can flash several times before landing on the correct content.

What workaround do I have for this? I was thinking of something similar to .net's SyncLock feature, but in javascript/jQuery. The ideal solution would be to cancel requests currently in the queue and start the new one.

One thing to note is that there might be multiple unrelated ajax requests going on so I can't clear all requests, just ones relating to this one div tag.


回答1:


Clearing/cancelling the request is an expensive task so uness you really need it dont do it. It also wont stop the execution on the server side, just close the httprequest.

What you should do is set a "lock" and lock and unlock it accordingly. Something like:

var working = false;

function startAjax() {
    working = true;
    // do ajax and wait for callback()
}

function callback() {
    working = false;
}

In the buttons .click() make sure you check if working before actual execution:

$("#thebutton1, #thebutton2").click(function() {
    if(working) {
        alert("Im in the middle of something");
    } else {
        // execute...
    }
});



回答2:


What you could do is to have the click event of all buttons that send output to the same div disable the button. Then in the AJAX callback, once you've processed the response, you can re-enable them all.



来源:https://stackoverflow.com/questions/2151638/jquery-ajax-synclock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!