在實(shí)戰(zhàn)中可能碰到的幾種ajax請(qǐng)求方法詳解
前言
最近在做一個(gè)針對(duì)單個(gè)節(jié)點(diǎn)測(cè)速的功能頁(yè)面,測(cè)速的邏輯是,測(cè)上傳速度時(shí),前端傳5m數(shù)據(jù)給server,記錄上傳和返回?cái)?shù)據(jù)的時(shí)間,測(cè)下載速度時(shí),從server下載1m的數(shù)據(jù),記錄下載和下載成功的時(shí)間,上傳和下載用的是ajax同步以避免客戶端帶寬阻塞的問(wèn)題,并進(jìn)行3次取平均值。在開(kāi)發(fā)過(guò)程過(guò),因?yàn)閍jax同步異步的問(wèn)題,走了不少?gòu)澛?,特地也把之前遇到的業(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ì)很冗長(zhǎng),解決的方法有兩個(gè),首先來(lái)看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的返回值,這樣寫起來(lái),代碼看起來(lái)會(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是給后端接收用的,前端通過(guò)動(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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- 淺析ajax請(qǐng)求json數(shù)據(jù)并用js解析(示例分析)
- Ajax請(qǐng)求中的異步與同步,需要注意的地方說(shuō)明
- 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)求成功后新開(kāi)窗口window.open()被攔截解決方法
- ajax 同步請(qǐng)求和異步請(qǐng)求的差異分析
相關(guān)文章
Ajax異步請(qǐng)求的五個(gè)步驟及實(shí)戰(zhàn)案例
通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,Ajax可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新,下面這篇文章主要給大家介紹了關(guān)于Ajax異步請(qǐng)求的五個(gè)步驟及實(shí)戰(zhàn)案例的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
解決IE下AjaxSubmit上傳文件提示下載文件問(wèn)題
這篇文章主要介紹了解決IE下AjaxSubmit上傳文件提示下載文件問(wèn)題,需要的朋友可以參考下2017-04-04
Ajax請(qǐng)求響應(yīng)中用window.open打開(kāi)新窗口被攔截的解決方法
ajax 異步請(qǐng)求成功后需要新開(kāi)窗口打開(kāi) url,使用的是 window.open() 方法,但是會(huì)被瀏覽器給攔截,怎么解決呢,下面小編給大家解答下2016-08-08
ajax的responseText亂碼的問(wèn)題的解決方法
javascript的編碼是和myeclipse一樣的為什么還會(huì)出現(xiàn)問(wèn)題,下面為大家介紹下ajax的responseText亂碼的問(wèn)題的解決方法2014-05-05
ajax AjaxDownloader.js[modified]
漏洞版本老啦,實(shí)用性不夠了,just have fun!2008-07-07

