gpt4 book ai didi

javascript - 带有 $.ajax 的 onreadystatechange 事件

转载 作者:行者123 更新时间:2023-11-29 16:14:36 26 4
gpt4 key购买 nike

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

使用 XMLHttpRequest我会做类似下面的事情(尽管我仍然不想使用 JQuery),JQuery 中是否还有一种方法可以访问 readystate 更改函数?是否有一个插件可以公开 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

最佳答案

你的意思是这样的吗:

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

关于javascript - 带有 $.ajax 的 onreadystatechange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18846135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com