【问题标题】:onreadystatechange event with $.ajax$.ajax 的 onreadystatechange 事件
【发布时间】:2014-12-09 06:28:08
【问题描述】:

我想使用来自 JQuery (2.0.2) $.ajax(...) 的(底层)XMLHttpRequestonreadystatechange 事件来触发同步 ajax 请求,这样我就可以向最终用户显示准确的状态指示,以便长时间运行要求。但似乎此功能已从最新版本的 JQuery 中删除(请参阅 here),使得具有异步 Web 请求的微调器成为向用户表示活动的唯一选项。

使用XMLHttpRequest 我会执行以下操作(尽管我仍然不想使用 JQuery),JQuery 中是否还有一种方法可以访问就绪状态更改功能?是否有可能公开onreadystatechange 事件的插件?

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

【问题讨论】:

    标签: javascript jquery ajax xmlhttprequest


    【解决方案1】:

    你的意思是这样的吗:

    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

    【讨论】:

    • 这个我找了很久!但是,是否有可能让它与 jQuery 1.11.0 一起使用?它似乎在那里不起作用。
    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多