jQuery $.ajax and readyStates

*爱你&永不变心* 提交于 2019-12-09 05:45:08

问题


How to call the Ajax ready states on the jQuery $.ajax method?


回答1:


$.ajax() returns the XmlHttpRequest object, so if you really want to access it as the state changes, you can do this:

var xhr = $.ajax({ ... });
xhr.onreadystatechange = function() { alert(xhr.readyState); };

But the built-in callbacks should be all you need for most uses, particularly success and complete.

To do things before the request fires, use beforeSend, or more appropriately for most cases, the .ajaxStart() and .ajaxStop() events...for example to show a loading message whenever any ajax activity is going on.




回答2:


Method, tested with jQuery 2.0.2:

$.ajax({
    beforeSend: function (jqXHR, settings) {
        var self = this;
        var xhr = settings.xhr;
        settings.xhr = function () {
            var output = xhr();
            output.onreadystatechange = function () {
                if (typeof(self.readyStateChanged) == "function") {
                    self.readyStateChanged(this);
                }
            };
            return output;
        };
    },
    readyStateChanged: function (xhr) {
        if (xhr.readyState == 1) {
            /* Connected! Do something */
        }
    },
    url: "..."
});

Basically, what I needed was a callback after readyState becomes 1 (Connected), which, in my case, was useful when implementing long polling "push" notifications with jQuery.




回答3:


You should be able to get all you need by setting callbacks for the success, error, and complete options in the object you pass into the ajax() method. Take a look at the documentation:

http://api.jquery.com/jQuery.ajax/

Basically, it works like this:

$.ajax({
    url: 'ajax/test.html',
    success: function(data) {
        alert('Load was performed.');
    },
    error: function() {alert("error occurred.")},
    complete: function() {alert("ajax complete.")}
});

You can see the docs for exactly what parameters you have access to in the callback functions.



来源:https://stackoverflow.com/questions/4107909/jquery-ajax-and-readystates

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