亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Jquery中巧用Ajax的beforeSend方法

 更新時(shí)間:2016年01月20日 17:23:54   作者:天空還下著雪  
這篇文章主要為大家介紹了Jquery中巧用Ajax的beforeSend方法,beforeSend方法用于在向服務(wù)器發(fā)送請(qǐng)求前添加一些處理函數(shù),需要的朋友可以參考下

jQuery是經(jīng)常使用的一個(gè)開源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)目開發(fā)中,提交表單時(shí)常常由于網(wǎng)絡(luò)或者其原因,用戶點(diǎn)擊提交按鈕誤認(rèn)為自己沒有操作成功,進(jìn)而會(huì)重復(fù)提交按鈕操作次數(shù),如果頁(yè)面前端代碼沒有做一些相應(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);
  }
});

方法beforeSend,用于在向服務(wù)器發(fā)送請(qǐng)求前添加一些處理函數(shù),希望通過(guò)這篇文章加深大家對(duì)beforeSend方法的學(xué)習(xí)認(rèn)識(shí)。

相關(guān)文章

最新評(píng)論