可以用 xhr.onload 替换 xhr.onreadystatechange 来进行 AJAX 调用吗?

2022-01-15 00:00:00 xmlhttprequest jquery javascript ajax

我只需要支持主流的现代浏览器(IE10+、FF、Chrome、Safari)

I need to support major modern browsers only (IE10+, FF, Chrome, Safari)

我可以做这个替换,因为我想简化我的代码库:

Can I make this substitution as I want to simplify my code base:

发件人:

xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            o.callback(xhr.responseText);
        } else {
            return false;
        }
    } else {
        return false;
    }
};

收件人:

xhr.onload = function (test) {
    o.callback(xhr.responseText);
};

我不认为 MDN 文档在这方面.

澄清:

我选择不使用框架.

推荐答案

也许你看看 这个并查看 W3C: XMLHttpRequest 如果你的浏览器支持 xhr.onload 也是一样的.需要 XMLHttpRequest 2)

maybe you take a look at this one and a look at W3C: XMLHttpRequest it's the same if your browser supports xhr.onload. Requires XMLHttpRequest 2)

如果 xhr.onload 不存在,您还可以编写一个模拟 xhr.onload 的包装函数.(我认为你需要重写 XMLHttpRequest.prototype.onload = function(args){//calling onreadystatechanges不知何故}).如果您只支持使用 xhr.onload 的现代浏览器,最好的解决方案是使用 framework(如 jquery 或 mootools 提供包装功能.

You can also write a wrapping function that emulates xhr.onload if it's not present. (I think you need to override XMLHttpRequest.prototype.onload = function(args){//calling onreadystatechanges somehow}). If you only support modern browsers using xhr.onload should be available - the best solution is using a framework (like jquery or mootools that provides wrapping functionality for that.

相关文章