开发过程中,发现jQuery中的ajax原本应该只发送一次请求,事实上却连续发送了多次。

解决办法是,在发送前作一个标记,检测是否已经发送过,成功或者失败再收回标记。

var th = $(this);
$.ajax({
        type: "GET",
        url:"/test.php",
        beforeSend: function(){
          if($(th).attr('data-sending')==1) return false;//如果已经在发送,则取消本次发送
          $(th).attr('data-sending','1');//发送前作标记,避免纠结的浏览器重复发送
          return true;
        },
        success: function(data){
          //发送成功的操作
          $(th).attr('data-sending','0');					
          return false;//取消其它操作,比如对超连接的点击事件
        },
        error: function(s){
          alert("ajax错误:"+s);
          $(th).attr('data-sending','0');
        }
      });

 

posted on 2012-09-18 02:40  setin  阅读(975)  评论(0编辑  收藏  举报