Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

javascript - Can one replace xhr.onreadystatechange with xhr.onload for AJAX calls?

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:

From:

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

To:

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

I don't feel that the MDN documentation is clear in this regard.

Clarification:

I choose not to use a framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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 or that provides wrapping functionality for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...