promise 的ajax 封装

let ajax = (obj) => {
    return new Promise((resolve, reject) => {
        let method = obj.method || 'GET';
        let xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        xhr.onReadyStateChange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                    resolve(xhr.responseText);
                } else {
                    reject(xhr.statusText);
                }
            }
        }
        if (method == 'POST') {
            xhr.open('POST', obj.url, true);
            
            
            //   =================下面两行为什么 get 时 没有  是没有必要吗?   
            xhr.responseType = "json";
            xhr.setRequestHeader("Accept", "application/json");
            xhr.send(obj.data);
        } else {
            let query = '';
            for (let key in obj.data) {
            //================================为什么用encodeURIComponent  可以直接写吗
                query += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]);
            }
            query.substring(1);
            xhr.open('GET', obj.url + '?' + query, true);
            xhr.send();
        }
    })
}
阅读 1.6k
1 个回答
下面两行为什么 get 时 没有 是没有必要吗

这里的 xhr.setRequestHeader("Accept", "application/json") 貌似有问题,应该是 ("Content-Type", "application/json") 才对吧?这里如果要直接 send 一个 js object 的话,是需要设定内容类型(Content-Type)的,毕竟这里不是作为 form 在发。
whatever,get 请求可以根据 url 后缀告诉后端合法的返回格式,比如 api.json 返回 json 、image.jpg 返回 jpg。作为一个接口,前后端应该也会约定具体的 accept 类型。而且无论 accept plaintext 还是 json,js 都是有能力进行解析的。

为什么用encodeURIComponent 可以直接写吗

不能,如果内容中有 url 特殊符号就会出问题,比如 & ? = 直接放到 url 里面会导致提前闭合解析错误。而且空格,中文,emoji 这些都有可能造成不可预知的错误。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题