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

前端 未结 4 1023
星月不相逢
星月不相逢 2020-12-08 06:30

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:

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 06:53

    You can clean up your first example by doing this

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

    Note, you probably want to check onload too with this.status === 200 if you are doing something with the else statement. Although, if you are checking for errors, there is also onerror, which you can write something like

    xhr.onerror = function(){
        console.log('Error: Do something else...');
    }
    

提交回复
热议问题