Query是經(jīng)常使用的一個(gè)開(kāi)源js框架,其中的$.ajax請(qǐng)求中有一個(gè)beforeSend方法只搁,用于在向服務(wù)器發(fā)送請(qǐng)求前執(zhí)行一些動(dòng)作。
具體可參考jQuery官方文檔:http://api.jquery.com/Ajax_Events/
$.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ò)或者其原因,用戶點(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è)例子:
// 提交表單數(shù)據(jù)到后臺(tái)處理
$.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) {
console.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") {
// ...
}
},
complete: function () {
$("loading").hide();
},
error: function (data) {
console.info("error: " + data.responseText);
}
});