表单重复提交

https://www.zhihu.com/question/19805411

 

https://czh7867480.github.io/2016/09/25/%E5%8E%9F%E5%88%9B-%E5%B7%A5%E4%BD%9C%E4%B8%ADbug%E8%A7%A3%E5%86%B3%E4%B9%8B-%E9%98%B2%E6%AD%A2Ajax%E9%87%8D%E5%A4%8D%E6%8F%90%E4%BA%A4/

1

$.ajax({
             url: 'login.do',
            data: $(this).closest('form[name="loginForm"]').serialize(),
            type: 'post',
             beforeSend: function () {
                 //3.让提交按钮失效,以实现防止按钮重复点击
                 $(loginBtn).attr('disabled', 'disabled');
                 
                //4.给用户提供友好状态提示
                 $(loginBtn).text('登录中...');
             },
            complete: function () {
                 //5.让登陆按钮重新有效
                 $(loginBtn).removeAttr('disabled');
             },
             success: function(msg){
                 
                 if (msg === 'ok') {
                     alert('登录成功!');
                     
                     //TODO 其他操作...
                 } else {
                     alert('登录失败,请重新登录!');
                 }
     
             }
         });

当只需要最后一次ajax

window.pendingRequests = {};
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  var key = options.url+Math.random();
  if (!pendingRequests[key] && key.indexOf('.html') == -1) {
      pendingRequests[key] =jqXHR;       
  }
  for(let i in pendingRequests)
      if(i!=key){
          pendingRequests[i].abort()
      }
  var complete = options.complete;
  options.complete = function (jqXHR, textStatus) {
      delete pendingRequests[key];
      if ($.isFunction(complete)) {
          complete.apply(this, arguments);
      }
  };
});

当只需要第一次ajax

window.pendingRequests = {};
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    var key=options.url;
    if (!pendingRequests[key] && key.indexOf('.html') == -1) {
        pendingRequests[key] =jqXHR;
    } else if (key.indexOf('.html') == -1) {
        jqXHR.abort();
    }
    var complete = options.complete;
    options.complete = function (jqXHR, textStatus) {
        delete pendingRequests[key];
        if ($.isFunction(complete)) {
            complete.apply(this, arguments);
        }
    };
});

 

posted @ 2017-09-26 10:33  hupan508  阅读(95)  评论(0编辑  收藏  举报