How to implement an ajax request queue using jQuery

孤者浪人 提交于 2019-12-09 13:40:00

问题


What is the best way to implement an Ajax request queue using jQuery? Specifically, I want to accomplish the following:

  • A user triggers any number of Ajax requests within a web page, which need to be queued up and submitted sequentially.

  • The web page needs to receive responses from the server and adjust itself accordingly.

  • Finally, if an error occurs (connection lost, server failed to respond, etc.), I want jQuery to invoke a JavaScript function.

I'm struggling with the last requirement in particular, as the error handling mechanism in jQuery's Ajax functions is not very intuitive. Are there any examples/tutorials that could help me with this task?

Thanks!


回答1:


I've made a few buffers like this. Some examples can be found simple task Buffer and deferred item queue.

As for error handling you can always use .ajaxError




回答2:


jQuery ajax has an error attribute where you can attach a function and the method will only fire if an error occurs. See the below example:

jQuery.ajax({
            type: "POST",
            url: "url",
            dataType:"json",
            data:{},
            success:function(data){                    
                alert("Succeed!");
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
            }    
        });

I hope you find this helpful.



来源:https://stackoverflow.com/questions/5601143/how-to-implement-an-ajax-request-queue-using-jquery

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