C语言 c++ php mysql nginx linux lnmp lamp lanmp memcache redis 面试 笔记 ppt 设计模式 问题 远程连接

如何终止正在在发送的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();
    }
}

 

 

 

posted on 2012-12-02 13:00  思齐_  阅读(26042)  评论(0编辑  收藏  举报