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)
                    }
                }
            }
        })
    }
}
相關文章
相關標籤/搜索