手动停止jquery ajax请求
主要调用jquery提供的ajax abort方法,详细代码如下:
1 <html> 2 <head> 3 <meta charset="UTF-8"> 4 <script src="http://apps.bdimg.com/libs/jquery/1.7.2/jquery.min.js"></script> 5 <script type="text/javascript"> 6 var ajax = null; 7 function startAjax() { 8 //方法就是将XHR对象指向ajax,再调用ajax的.abort()来中止请求 9 ajax = $.ajax({ 10 type: 'POST', 11 url: 'test.php', 12 data: { 13 username: "test" 14 }, 15 dataType: 'JSON', 16 error: function() { 17 console.log('error'); 18 }, 19 success: function(data) { 20 console.log(data); 21 } 22 }); 23 } 24 function stopAjax(){ 25 //如若上一次AJAX请求未完成,则中止请求 26 ajax&&ajax.abort(); 27 } 28 </script> 29 </head> 30 <body> 31 <input type="button" value="触发请求" onclick="startAjax()" /> 32 <input type="button" value="停止请求" onclick="stopAjax()" /> 33 </body> 34 </html>
test.php
1 <?php 2 // 休眠6秒之后在进行后续流程,方便测试停止事件 3 sleep(6); 4 echo '{"username": "'.$_POST['username'].'"}'; 5 ?>