99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學(xué)院 頭像
蘋果6袋
6
麥子學(xué)院

Jquery中如何解決ajax重復(fù)提交問題?

發(fā)布時(shí)間:2016-10-18 19:14  回復(fù):0  查看:3310   最后回復(fù):2016-10-18 19:14  
在jquery開發(fā)中,我們常常遇到ajax重復(fù)提交問題,那如何解決ajax的重復(fù)提交呢?本文就將重點(diǎn)和大家分享這部分內(nèi)容,一起來看看吧,希望可以幫助大家更好的學(xué)習(xí)ajax。

  ``` /* * jquery ajax請求過濾,防止ajax請求重復(fù)發(fā)送,對ajax發(fā)送錯(cuò)誤時(shí)進(jìn)行統(tǒng)一處理 / $(function(){ var pendingRequests = {}; // 所有ajax請求的通用前置filter $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { var key = generatePendingRequestKey(options);

  //請求是否已經(jīng)存在
  if(!pendingRequests[key]){
  storePendingRequest(key,jqXHR);
  }else{
  //如果ajax請求已經(jīng)存在,下一次相同的請求則取消,防止重復(fù)請求
  jqXHR.abort();
  }

  //ajax請求完成時(shí),從臨時(shí)對象中清除請求對應(yīng)的數(shù)據(jù)
  var complete = options.complete;
  options.complete = function(jqXHR, textStatus) {
  //延時(shí)1000毫秒刪除請求信息,表示同Key值請求不能在此時(shí)間段內(nèi)重復(fù)提交
  setTimeout(function(){
  delete pendingRequests[jqXHR.pendingRequestKey];
  },1000);

  if ($.isFunction(complete)) {
  complete.apply(this, arguments);
  }
  };

  //統(tǒng)一的錯(cuò)誤處理
  var error = options.error;
  options.error = function(jqXHR, textStatus) {
  errorHandler(jqXHR, textStatus);
  if ($.isFunction(error)) {
  error.apply(this, arguments);
  }
  };
  });

  /**
  * 當(dāng)ajax請求發(fā)生錯(cuò)誤時(shí),統(tǒng)一進(jìn)行攔截處理的方法
  */
  function errorHandler(jqXHR, textStatus){
  switch (jqXHR.status){
  case(500):
  internalError(jqXHR);
  break;
  case(403):
  accessDenied(jqXHR);
  break;
  case(408):
  timeoutError(jqXHR);
  break;
  case(404):
  pageNotFound(jqXHR);
  break;
  default:
  //otherError(jqXHR, textStatus);
  }
  }

  function pageNotFound(jqXHR){
  Component.warningMessageBox({
  content:"請求訪問的地址或內(nèi)容不存在!"
  });
  }

  function accessDenied(jqXHR){
  Component.warningMessageBox({
  content:"你無權(quán)進(jìn)行此操作或頁面訪問!"
  });
  }

  function internalError(jqXHR){
  Component.warningMessageBox({
  content:"服務(wù)器存在錯(cuò)誤,未能正確處理你的請求!"
  });
  }

  function timeoutError(jqXHR){
  window.location.href=contextPath + "/j_spring_security_logout";
  }

  function otherError(jqXHR, textStatus){
  Component.warningMessageBox({
  content:"未知錯(cuò)誤,錯(cuò)誤代碼:" + textStatus
  });
  }

  /**
  * 將ajax請求存儲到臨時(shí)對象中,用于根據(jù)key判斷請求是否已經(jīng)存在
  */
  function storePendingRequest(key, jqXHR){
  pendingRequests[key] = jqXHR;
  jqXHR.pendingRequestKey = key;
  }

  /**
  * 根據(jù)ajax請求參數(shù)構(gòu)建一個(gè)臨時(shí)存儲key,此處簡單的使用url作為key,
  * 不考慮為解決請求類型為get時(shí)相同路徑引起的緩存問題,采用隨機(jī)碼構(gòu)建URL的情況
  */
  function generatePendingRequestKey(options){
  return options.url;
  }
  });


  文章來源:極客頭條
您還未登錄,請先登錄

熱門帖子

最新帖子

?