XMLHttpRequest之onreadystatechange

2022-12-15 15:16:02 浏览数 (1)

XMLHttpRequest之onreadystatechange

代码语言:javascript复制
function doReq(url, fn){
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        if(this.readyState == XMLHttpRequest.DONE){
            return fn(this);
        }
    }
    req.open('GET', url, false);
    req.send();
}
var res;
function myreq(xhttp){
    try{
        switch(xhttp.status){
            case 200:
                res = xhttp.responseText;
                break;
            case 404:
                throw new Error('404');
                break;
            case 500:
                throw new Error('500');
                break;
            default:
                throw new Error(xhttp.status);
                break;
        }
    }catch(e){
        res = e.message;
    }
}
doReq('https://www.w3school.com.cn/demo/js/ajax_info.txt', myreq);
console.log(res);

本文采用 「CC BY-NC-SA 4.0」创作共享协议,转载请标注以下信息:

原文出处:Yiiven https://cloud.tencent.com/developer/article/2193263

0 人点赞