js網(wǎng)絡(luò)請(qǐng)求匯總

1.原生XHR

var xhr = new XMLHttpRequest()
//xhr.responseType = 'json'可以將返回json字符串結(jié)果自動(dòng)轉(zhuǎn)換成對(duì)象
xhr.open(method,  uri,  true)
xhr.send('body')//請(qǐng)求主體(上傳的參數(shù))
xhr.onreadystatechange = function(){        
    if(xhr.readyState===4){     
        if(xhr.status>=200 && xhr.status<300){ //響應(yīng)完成且成功        
            console.log(xhr.responseText);
        }else{  //響應(yīng)完成但不成功
            alert('響應(yīng)完成但失?。?+xhr.status);
        }       
    }       
}

2.JQuery--AJAX

//需引入JQuery <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
$.ajax({
    url: '/add/',  // 請(qǐng)求地址
    method: 'post',  // 請(qǐng)求方式
    data:{'a':$("#first").val() ,'b':$("#second").val() },  //  獲取input標(biāo)簽數(shù)據(jù)
    success:function (data) {
        //成功觸發(fā)
    },
    error:function (error) {
        //失敗,觸發(fā)
    }
})

好處:可以將對(duì)象數(shù)據(jù)自動(dòng)序列化成對(duì)應(yīng)的請(qǐng)求頭對(duì)應(yīng)形式的數(shù)據(jù)

3.原生fetch

  • Fetch API是新的ajax解決方案Fetch會(huì)返回Promise
  • fetch不是ajax的進(jìn)一步封裝,而是原生js,沒(méi)有使用XMLHttpRequest對(duì)象。

語(yǔ)法:fetch(url, options).then()

fetch(url, {
    //body: JSON.stringify(data), // body(上傳的數(shù)據(jù))需要對(duì)應(yīng)header中的'Content-Type',序列化成不同的字符串形式
    body:'key=value&key=value',
    headers: {
        //'content-type': 'application/json'
        'content-type':'application/x-www-form-urlencoded'
    },
    method: 'POST', // *GET默認(rèn)get請(qǐng)求, POST, PUT, DELETE, etc.
})

4.axios

  • Axios 是一個(gè)基于 promiseHTTP 庫(kù),可以用在瀏覽器和 node.js
  • 特點(diǎn):
    • 從瀏覽器中創(chuàng)建 XMLHttpRequests
    • node.js 創(chuàng)建 http 請(qǐng)求
    • 支持 Promise API
    • 攔截請(qǐng)求和響應(yīng)
  1. 語(yǔ)法
    ①. 安裝:npm install axios -S
    或者靜態(tài)引入:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    ②. 使用請(qǐng)求方式
    get方式

            // 為給定 ID 的 user 創(chuàng)建請(qǐng)求
                axios.get('/user?ID=12345')
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });

                // 可選地,上面的請(qǐng)求可以這樣做
                axios.get('/user', {
                    params: {
                    ID: 12345
                    }
                })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        post方式 

            axios.post('/login',qs.stringify({
                user:'xxx',
                pwd:'密碼'
            }))
            .then(res=>{
                console.log(res);
                console.log(res.data);
            })

③. 執(zhí)行多個(gè)并發(fā)請(qǐng)求

       function getUserAccount() {
           return axios.get('/user/12345');
       }

       function getUserPermissions() {
           return axios.get('/user/12345/permissions');
       }

       axios.all([getUserAccount(), getUserPermissions()])
           .then(axios.spread(function (acct, perms) {
               // 兩個(gè)請(qǐng)求現(xiàn)在都執(zhí)行完成
       }));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容