巧用Ajax的beforeSend 提升用戶體驗

jQuery是常用的一個開源js框架,其中的$.ajax請求中有一個beforeSend方法,用於在向服務器發送請求前執行一些動做。
具體可參考jQuery官方文檔:http://api.jquery.com/Ajax_Events/前端

1 $.ajax({
2     beforeSend: function(){
3      // Handle the beforeSend event
4     },
5     complete: function(){
6      // Handle the complete event
7     }
8     // ......
9 });

防止重複數據

在實際項目開發中,提交表單時經常因爲網絡或者其緣由,用戶點擊提交按鈕誤認爲本身沒有操做成功,進而會重複提交按鈕操做次數,若是頁面前端代碼沒有作一些相應的處理,一般會致使多條一樣的數據插入數據庫,致使髒數據的增長。要避免這種現象,在$.ajax請求中的beforeSend方法中把提交按鈕禁用掉,等到Ajax請求執行完畢,在恢復按鈕的可用狀態。jquery

舉個例子:ajax

 1 // 提交表單數據到後臺處理
 2 $.ajax({
 3     type: "post",
 4     data: studentInfo,
 5     contentType: "application/json",
 6     url: "/Home/Submit",
 7     beforeSend: function () {
 8         // 禁用按鈕防止重複提交
 9         $("#submit").attr({ disabled: "disabled" });
10     },
11     success: function (data) {
12         if (data == "Success") {
13             //清空輸入框
14             clearBox();
15         }
16     },
17     complete: function () {
18         $("#submit").removeAttr("disabled");
19     },
20     error: function (data) {
21         console.info("error: " + data.responseText);
22     }
23 });

模擬Toast效果

ajax請求服務器加載數據列表時提示loading(「加載中,請稍後...」),數據庫

 1 $.ajax({
 2     type: "post",
 3     contentType: "application/json",
 4     url: "/Home/GetList",
 5     beforeSend: function () {
 6         $("loading").show();
 7     },
 8     success: function (data) {
 9         if (data == "Success") {
10             // ...
11         }
12     },
13     complete: function () {
14         $("loading").hide();
15     },
16     error: function (data) {
17         console.info("error: " + data.responseText);
18     }
19 });
相關文章
相關標籤/搜索