beforeSend方法的用戶主要有下面幾個:
第一:用於在發送ajax請求之前設置請求頭
即作為前端,如果我們希望在發送數據之前設置請求頭,就可以像下面這么做:
beforeSend: function(request) { request.setRequestHeader("BBG-Key", "ab9ef204-3253-49d4-b229-3cc2383480a6"); },
第二:防止數據重復
當用戶提交表單時,雖然有時候已經點擊了提交按鈕,但是由於網絡原因,會出現暫時沒有返回數據等情況,用戶會認為沒有點擊成功,就會造成數據庫中產生多條重復的數據---臟數據,所以我們可以在beforeSend中添加禁用提交按鈕的功能,在complete后在恢復之,如下:
// 提交表單數據到后台處理 $.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); } });