onreadystatechange事件与$阿贾克斯 [英] onreadystatechange event with $.ajax

查看:107
本文介绍了onreadystatechange事件与$阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从(底层) 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

这篇关于onreadystatechange事件与$阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆