xvno / blog

个人博客, 不定期发布技术笔记和个人随笔.
0 stars 0 forks source link

JS: XMLHttpRequest, fetch, axios #123

Open xvno opened 3 years ago

xvno commented 3 years ago

XMLHttpRequest

先来一段示例代码

function fetchit(url, opt, cb) {
    let xhr = new XMLHttpRequest();
    let method = opt && opt.method || 'GET';
    xhr.open(method, url);
    if (opt && opt.headers) {
        xhr.setRequestHeader(opt.headers);
    }
    xhr.onreadystatechange = function () {
        let headers = xhr.getResponseHeader();
        let state = xhr.status;
        let stateMsg = xhr.statusText;
        let ret = { headers, state, msg };
        ret.data = xhr.response;
        cb(ret);
    };
    xhr.onerror = function (error) {
        cb({ error });
    };
    xhr.onload = function () {

    }
    xhr.onprogress = function () {

    }
    xhr.send();
}