onreadystatechange事件与$阿贾克斯事件、onreadystatechange、阿贾克斯

由网友(城南花开)分享简介:我想从(底层) XMLHtt prequest jQuery的的使用的onreadystatechange 事件(2.0 。2) $。阿贾克斯(...)火同步Ajax请求,所以我可以显示正确的状态指示给最终用户对于长时间运行的请求。但似乎这个功能已经从JQuery的最新版本中删除(见这里),使纺纱用异步Web请求的仅...

我想从(底层) XMLHtt prequest jQuery的的使用的onreadystatechange 事件(2.0 。2) $。阿贾克斯(...)火同步Ajax请求,所以我可以显示正确的状态指示给最终用户对于长时间运行的请求。但似乎这个功能已经从JQuery的最新版本中删除(见这里),使纺纱用异步Web请求的仅的选项重新presenting活动给用户。

I want to use the onreadystatechange event from the (underlying) XMLHttpRequest of JQuery's (2.0.2) $.ajax(...) to fire synchronous ajax requests so I can show an accurate status indication to the end user for long running requests. But it seems this functionality has been removed from the latest version of JQuery (see here), making spinners with asynchronous web requests the only option for representing the activity to the user.

使用 XMLHtt prequest 我会做类似如下(虽然我仍然wan't使用jQuery),是否仍有办法在JQuery中获得访问readyState的改变功能?是否有可能是一个插件,公开的onreadystatechange 事件?

using XMLHttpRequest I would do something like the following (though I still wan't to use JQuery), is there still a way in JQuery to gain access to a readystate change function? Is there perhaps a plugin that exposes the onreadystatechange event?

function pad(width, string, padding) { // from stackoverflow.com/a/15660515/424963 
  return (width <= string.length) ? string : pad(width, string + padding, padding)
}

$(function(){
    $("<div>Loading</div>").appendTo($("body"));
    var anticache = "?anticache=" + new Date().getTime();

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4){
            $("div").html("Done");
        }
        else  {
            $("div").html("Loading" + pad(xhr.readyState, "", "."));
        }
    };

    xhr.open("POST", "jsfiddle.net" + anticache, true );
    xhr.send();    
});

的jsfiddle

推荐答案

你的意思是这样的:

var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
    var xhr = _orgAjax();
    xhr.onreadystatechange = function() {
        //you can log xhr.readystate here
        if( xhr.readyState == 4 ) {
             $("div").html("Done");
        }
    }
    return xhr;
};
$(function(){
    $("<div>Loading</div>").appendTo($("body"));
    var anticache = "?anticache=" + new Date().getTime();
    $.ajax({
        url: "http://fiddle.jshell.net",
        error: function() {
            console.log("error");
        }
    });
});

演示:: 的jsfiddle

阅读全文

相关推荐

最新文章