jQuery是經常使用的一個開源js框架,其中的$.ajax請求中有一個beforeSend方法,用於在向服務器發送請求前執行一些動作。
具體可參考jQuery官方文檔:http://api.jquery.com/Ajax_Events/
$.ajax({beforeSend: function(){// Handle the beforeSend event},complete: function(){// Handle the complete event}// ......});
防止重復數據
在實際項目開發中,提交表單時常常由於網絡或者其原因,用戶點擊提交按鈕誤認為自己沒有操作成功,進而會重復提交按鈕操作次數,如果頁面前端代碼沒有做一些相應的處理,通常會導致多條同樣的數據插入數據庫,導致臟數據的增加。要避免這種現象,在$.ajax請求中的beforeSend方法中把提交按鈕禁用掉,等到Ajax請求執行完畢,在恢復按鈕的可用狀態。
舉個例子:
// 提交表單數據到后台處理$.ajax({type: "post",data: studentInfo,contentType: "application/json",url: "/Home/Submit",beforeSend: function () {// 禁用按鈕防止重復提交$("#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請求服務器加載數據列表時提示loading(“加載中,請稍后...”),
$.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);}});