欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js与jQuery终止正在发送的ajax请求的方法

程序员文章站 2022-06-03 15:05:23
本文实例讲述了js与jquery终止正在发送的ajax请求的方法。分享给大家供大家参考,具体如下: 核心:调用xmlhttprequest对象上的abort方法 jqu...

本文实例讲述了js与jquery终止正在发送的ajax请求的方法。分享给大家供大家参考,具体如下:

核心:调用xmlhttprequest对象上的abort方法

jquery的ajax方法有自己的超时时间设置参数:

$.ajax({type:'post',
  url:'b.php',
  data:'',
  timeout:5000,
  success:function(){
  }
})

同时

1. $.get返回的数据类型是xmlhttprequest,请参考手册。($.post、$.ajax、$.getjson、$.getscript也同样)

2. xmlhttprequest对象有abort()方法

也可以自己手动去调用abort方法:

<script src = "jquery-1.4.4.js"></script>
<script>
var xhr = $.ajax({type:'post',
  url:'b.php',
  data:'',
  success:function(){
    alert('ok');
  }
})
alert(xhr);
console.log(xhr);
</script>
<button id="song">abort</button>
<script>
$(function(){
  $("#song").click(function(){
    alert('click');
    xhr.abort();
  })
})
</script>

对于原生的xhr:

xmlhttp.open("post","theurl",true);
xmlhttp.onreadystatechange=function(){
  ...//得到响应之后的操作
}
xmlhttp.send();
//设置8秒钟后检查xmlhttp对象所发送的数据是否得到响应.
settimeout("checkrequest()","8000");
function checkrequest(){
  //为4时代表请求完成了  
  if(xmlhttp.readystate!=4){
    alert('响应超时');
    //关闭请求
    xmlhttp.close();
  }
}

希望本文所述对大家ajax程序设计有所帮助。