jQuery $.ajax and readyStates

2020-06-03 08:38发布

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

3条回答
甜甜的少女心
2楼-- · 2020-06-03 09:18

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楼-- · 2020-06-03 09:30

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-06-03 09:40

$.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.

查看更多
登录 后发表回答