jQuery是經(jīng)常使用的一個(gè)開(kāi)源js框架,其中的$.ajax請(qǐng)求中有一個(gè)beforeSend方法,用于在向服務(wù)器發(fā)送請(qǐng)求前執(zhí)行一些動(dòng)作。
$.ajax({
beforeSend:function(){
// handle the beforeSend event
},
complete:function(){
// handle the complete event
}
});
防止重復(fù)數(shù)據(jù)
在實(shí)際項(xiàng)目開(kāi)發(fā)中,提交表單時(shí)常常由于網(wǎng)絡(luò)或者其原因,用戶(hù)點(diǎn)擊提交按鈕誤認(rèn)為自己沒(méi)有操作成功,進(jìn)而會(huì)重復(fù)提交按鈕操作次數(shù),如果頁(yè)面前端代碼沒(méi)有做一些相應(yīng)的處理,通常會(huì)導(dǎo)致多條同樣的數(shù)據(jù)插入數(shù)據(jù)庫(kù),導(dǎo)致臟數(shù)據(jù)的增加。要避免這種現(xiàn)象,在$.ajax請(qǐng)求中的beforeSend方法中把提交按鈕禁用掉,等到Ajax請(qǐng)求執(zhí)行完畢,在恢復(fù)按鈕的可用狀態(tài)。
舉個(gè)例子:
$.ajax({
type:"post",
data:studentInfo,
contentType:"application/json",
url:"/Home/Submit",
beforeSend:function(){
//禁用按鈕防止重復(fù)提交
$("#submit).attr({disabled:"disabled"});
},
success:function(data){
if(data=="Success"){
// 清空輸入框
clearBox();
}
},
complete:function(){
$("#submit").removeAttr("disabled");
},
error:function(data){
consloe.info("error:"+data.responseText);
}
});
模擬Toast效果
ajax請(qǐng)求服務(wù)器加載數(shù)據(jù)列表時(shí)提示loading(“加載中,請(qǐng)稍后...”)
$.ajax({
type:"post",
contentType:"application/json",
url:"/Home/GetList",
beforeSend: function(){
$("loading").show();
},
success: function(data){
if (data=="Success"){
// ...
}
},
error: function(){
console.info("error:"+data.responseText);
}
});
以上這篇淺析巧用Ajax的beforeSend提高用戶(hù)體驗(yàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。