jQuery $.ajax and readyStates

2020-06-03 08:50发布

问题:

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.