ajax与Fetch

1、ajaxajax

  • 使用步骤
    1.建立XmlHttpRequest对象
    2.调用open方法设置基本请求信息
    3.设置发送的数据,发送请求
    4.注册监听的回调函数
    5.拿到返回值,对页面进行更新
//1.建立Ajax对象
    if(window.XMLHttpRequest){
       var oAjax=new XMLHttpRequest();
    }else{
       var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
    }

    //2.链接服务器(打开和服务器的链接)
    oAjax.open('GET', url, true);

    //3.发送
    oAjax.send();

    //4.接收
    oAjax.onreadystatechange=function (){
       if(oAjax.readyState==4){
           if(oAjax.status==200){
              //alert('成功了:'+oAjax.responseText);
              fnSucc(oAjax.responseText);
           }else{
              //alert('失败了');
              if(fnFaild){
                  fnFaild();
              }
           }
        }
    };

2、fetchjson

  • 特色
    一、第一个参数是URL:
    二、第二个是可选参数,能够控制不一样配置的 init 对象
    三、使用了 JavaScript Promises 来处理结果/回调:
fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

你能够经过Request构造器函数建立一个新的请求对象,你还能够基于原有的对象建立一个新的对象。 新的请求和旧的并无什么不一样,但你能够经过稍微调整配置对象,将其用于不一样的场景。例如:promise

var req = new Request(URL, {method: 'GET', cache: 'reload'});
fetch(req).then(function(response) {
  return response.json();
}).then(function(json) {
  insertPhotos(json);
});

上面的代码中咱们指明了请求使用的方法为GET,而且指定不缓存响应的结果,你能够基于原有的GET请求建立一个POST请求,它们具备相同的请求源。代码以下:缓存

// 基于req对象建立新的postReq对象
var postReq = new Request(req, {method: 'POST'});

fetch和ajax 的主要区别

一、fetch()返回的promise将不会拒绝http的错误状态,即便响应是一个HTTP 404或者500
二、在默认状况下 fetch不会接受或者发送cookies服务器

fetch的配置

Promise fetch(String url [, Object options]);
Promise fetch(Request req [, Object options]);cookie

fetch封装

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',//为了在当前域名内自动发送 cookie , 必须提供这个选项
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "cors",//请求的模式
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        
        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}
相关文章
相关标签/搜索