在實(shí)戰(zhàn)中可能碰到的幾種ajax請(qǐng)求方法詳解
前言
最近在做一個(gè)針對(duì)單個(gè)節(jié)點(diǎn)測(cè)速的功能頁面,測(cè)速的邏輯是,測(cè)上傳速度時(shí),前端傳5m數(shù)據(jù)給server,記錄上傳和返回?cái)?shù)據(jù)的時(shí)間,測(cè)下載速度時(shí),從server下載1m的數(shù)據(jù),記錄下載和下載成功的時(shí)間,上傳和下載用的是ajax同步以避免客戶端帶寬阻塞的問題,并進(jìn)行3次取平均值。在開發(fā)過程過,因?yàn)閍jax同步異步的問題,走了不少彎路,特地也把之前遇到的業(yè)務(wù)邏輯整理匯總一下。
ajax請(qǐng)求方法如下
一、普通的ajax,async即同步異步處理,success之后,會(huì)有data返回值,status請(qǐng)求狀態(tài),xhr封裝的是請(qǐng)求頭,但要注意是的是,并不是所有的請(qǐng)求頭信息都能獲取到的,比如center-length就獲取不到
$.ajax({ type: "GET", async: true, //異步執(zhí)行 默認(rèn)是true異步 url: url, dataType: "json", // jsonp: "callback", success: function(data, status, xhr){ console.log(data);//返回值 console.log(status);//狀態(tài) console.log(xhr);//obj console.log(xhr.getResponseHeader("Content-Type"));//application/octet-stream console.log(xhr.getResponseHeader("Center-Length"));//null } });
二、有時(shí)候碰到的業(yè)務(wù)邏輯是這樣的,請(qǐng)求2依賴請(qǐng)求1的返回結(jié)果,請(qǐng)求3依賴請(qǐng)求2的返回結(jié)果,如果用回調(diào)的方式寫,會(huì)很冗長,解決的方法有兩個(gè),首先來看ES5的解決辦法
(1)ES5的解決辦法,用ajax同步,默認(rèn)的ajax是異步的,即多個(gè)請(qǐng)求同時(shí)執(zhí)行,改成同步后,ajax一個(gè)一個(gè)的執(zhí)行,這樣ajax2就能取到ajax1的返回結(jié)果了
let res1 = "" let res2 = "" $.ajax({ type: 'get', async: false, //同步執(zhí)行 默認(rèn)是true異步 url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime(), dataType: 'json', success: function(res) { if(res.code == 0){ res1 = res.data.bandwidth[0] }else{ } } }); $.ajax({ type: 'get', async: false, //同步執(zhí)行 默認(rèn)是true異步 url: pars.domain + "/api.php?Action=xxx&date=2017-03-08&dom1111" + res1 + "&t=" + (new Date).getTime(), dataType: 'json', success: function(res) { if(res.code == 0){ res2 = res.data.bandwidth[0] }else{ } } });
(2)ES6的解決辦法,用promise的then方法,效果和上面的一樣,ajax會(huì)按順序執(zhí)行,并且后面的ajax會(huì)拿到前一個(gè)ajax的返回值,這樣寫起來,代碼看起來會(huì)很流暢
let pro = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); console.log('請(qǐng)求pro成功'); }); //用then處理操作成功,catch處理操作異常 pro.then(requestA) .then(requestB) .then(requestC) .catch(requestError); function requestA(res){ console.log('上一步的結(jié)果:'+res); console.log('請(qǐng)求A成功'); let proA = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proA } function requestB(res){ console.log('上一步的結(jié)果:'+res); console.log('請(qǐng)求B成功'); let proB = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proB } function requestC(res){ console.log('上一步的結(jié)果:'+res); console.log('請(qǐng)求C成功'); let proC = new Promise(function(resolve,reject){ let url = pars.domain + "/api.php?Action=xxx&date=2017-03-08&t=" + (new Date).getTime() let ajax = $.get(url, function(res) { if (res.code == 0) { resolve(resData); } else{ } }, "json"); }); return proC } function requestError(){ console.log('請(qǐng)求失敗'); }
三、jsonp跨域,動(dòng)態(tài)添加script標(biāo)簽實(shí)現(xiàn)跨域,注意這里有一個(gè)callback需要跟server協(xié)商好
function switchEngineRoomAjax(api,statusChanged){ var api = api; var statusChanged = statusChanged; var url = api + "?method=setStatus" + "&status=" + statusChanged; $.ajax({ type: "GET", url: url, dataType: "jsonp", jsonp: "callback",// 這里的callback是給后端接收用的,前端通過動(dòng)態(tài)添加script標(biāo)簽,完成回調(diào) success: function(res){ if (res.code == 0) { console.log('更改狀態(tài) jsonp獲取數(shù)據(jù)成功!'); } else{ } } }); };
四、還會(huì)碰上這種業(yè)務(wù)邏輯,ajax1 ajax2 ajax3三個(gè)異步請(qǐng)求,不一定哪個(gè)先返回?cái)?shù)據(jù),都請(qǐng)求成功后,執(zhí)行一個(gè)回調(diào) function,需要注意的是,單獨(dú)的ajax也需要是new的promise
ajax1:function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryLog完成!'); } else{ } }, "json"); }); return promise }, ajax2: function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryGroupNodeList完成!'); } else{ } }, "json"); }); return promise }, ajax3: function(){ var promise = new Promise(function (resolve, reject) { var url = "/api.php?Action=xxx; $.get(url, function(res) { if (res.code == 0) { resolve('queryGroupNodeMapList完成!'); } else{ } }, "json"); }); return promise }, initQuery: function(){ var mySelf = this; var promiseList = []; var ajax1Promise = mySelf.ajax1(); var ajax2Promise = mySelf.ajax2(); var ajax3Promise = mySelf.ajax3(); promiseList.push(ajax1Promise,ajax2Promise,ajax3Promise); var p1 = new Promise(function (resolve, reject) { console.log('創(chuàng)建1.2秒延時(shí)執(zhí)行promise'); setTimeout(function () { resolve("1.2秒延時(shí)執(zhí)行promise"); }, 1200); }); promiseList.push(p1) Promise.all(promiseList).then(function (result) { console.log('ajax全部執(zhí)行完畢:' + JSON.stringify(result)); // ["Hello", "World"] mySelf.assembleTableData(); }); },
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- 淺析ajax請(qǐng)求json數(shù)據(jù)并用js解析(示例分析)
- Ajax請(qǐng)求中的異步與同步,需要注意的地方說明
- AJAX跨域請(qǐng)求json數(shù)據(jù)的實(shí)現(xiàn)方法
- Ajax請(qǐng)求內(nèi)嵌套Ajax請(qǐng)求示例代碼
- 如何將ajax請(qǐng)求返回的Json格式數(shù)據(jù)循環(huán)輸出成table形式
- Ajax請(qǐng)求在數(shù)據(jù)量大的時(shí)候出現(xiàn)超時(shí)的解決方法
- 多ajax請(qǐng)求的各類解決方案(同步, 隊(duì)列, cancel請(qǐng)求)
- ajax請(qǐng)求亂碼的解決方法(中文亂碼)
- ajax請(qǐng)求成功后新開窗口window.open()被攔截解決方法
- ajax 同步請(qǐng)求和異步請(qǐng)求的差異分析
相關(guān)文章
ajax結(jié)合mysql數(shù)據(jù)庫和smarty實(shí)現(xiàn)局部數(shù)據(jù)狀態(tài)的刷新方法
下面小編就為大家分享一篇ajax結(jié)合mysql數(shù)據(jù)庫和smarty實(shí)現(xiàn)局部數(shù)據(jù)狀態(tài)的刷新方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12Ajax實(shí)現(xiàn)簡單下拉選項(xiàng)效果【推薦】
下面小編就為大家?guī)硪黄狝jax實(shí)現(xiàn)簡單下拉選項(xiàng)效果【推薦】。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,一起跟隨小編過來看看吧2016-04-04herf=#導(dǎo)致Ajax請(qǐng)求時(shí)沒有向后臺(tái)發(fā)送數(shù)據(jù)
當(dāng)點(diǎn)擊重命名進(jìn)行Ajax請(qǐng)求時(shí),并沒有向后臺(tái)發(fā)送數(shù)據(jù)而是直接跳轉(zhuǎn)到了首頁,后來發(fā)現(xiàn)是這個(gè)herf=#惹的禍2014-05-05JavaScript操作表單_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
用JavaScript操作表單和操作DOM是類似的,因?yàn)楸韱伪旧硪彩荄OM樹。下面通過本文給大家介紹JavaScript操作表單的相關(guān)知識(shí),感興趣的朋友一起看看吧2017-06-06AJax 把拿到的后臺(tái)數(shù)據(jù)在頁面中渲染的實(shí)例
今天小編就為大家分享一篇AJax 把拿到的后臺(tái)數(shù)據(jù)在頁面中渲染的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08