ajax cancels the handling of pending requests

  • 2020-05-30 19:43:49
  • OfStack

When we switch tabs, if we are using ajax technology, we will encounter the following situation: when we click on tab1, the server makes an Ajax request to get the content data of tab1. If the request is being processed, and in the process you click on the tab2 option and send a new request, the server now has two requests pending. The result is that when the data content is displayed, the content data for the tab1 option is displayed first, followed by the tab2 option. In this case, we should cancel the pending request of tab1 and only allow the processing of the current (tab2) request to create a new index.html code as follows:


<style><!--
*{margin:0;padding:0;}
li{list-style-type:none;}
.tab{
width:240px;
margin: 50px auto;
}
.nav ul{
clear:both;
}
.nav ul li{
margin-right: 4px;
padding: 1px 6px;
border:1px solid #ccc;
width:60px;
background: #f1f1f1;
float: left;
text-align: center;
cursor: pointer;
}
.nav ul li.selected{
color:#fff;background:blue;
}
#box{
width:238px;
border: 1px solid #ccc;
height: 100px;
clear: both;
overflow: hidden;
}
.addBg{
background: url('./img/loading.gif') no-repeat center;
}
--></style>
<script type="text/javascript" src="https://www.ofstack.com/itoks/admin/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(function()
{
var ajax;
$.ajax({
type: 'GET',
url: '4.php',
data: 'what=1',
success:function(data)
{
// Remove the small icon after successful loading 
// $("#box").removeClass("addBg");
// $('#box').html(data);
$("#box").removeClass("addBg").html(data);
},
beforeSend:function() //
{
// You have to wait for small ICONS during loading , Clears out box The content of the 
$("#box").html('').addClass("addBg");
}
});
$('.nav ul li').click(function()
{
$(this).addClass('selected')
.siblings().removeClass('selected');
var liName = $(this).attr('name');
//alert(liName);
// You have to wait for small ICONS during loading , Clears out box The content of the 
$("#box").html('').addClass("addBg");
if(ajax)
{
ajax.abort();
//alert(ajax);
}
ajax = $.get(
'4.php',
{what : liName},
function(data)
{
// Remove the small icon after successful loading 
$("#box").removeClass("addBg");
$('#box').html(data);
}
);
});
});
// ]]></script>
<div class="tab">
<div class="nav">
<ul>
<li class="selected">tab 1</li>
<li>tab 2</li>
<li>tab 3</li>
</ul>
</div>
<div id="box">&nbsp;</div>
</div>

Create another 4.php file code as follows:

<?php 
sleep(1); 
if(isset($_GET['what'])) 
{ 
switch($_GET['what'])
{ 
case 1: echo '111111111111111';
break; 
case 2:
echo '22222222222222222';
break;
case 3:
echo '33333333333333333';
break;
default: echo ' No content '; 
}
}
?>

I'm going to make a folder js,
Inside is a file called jquery-1.4.4.e.22en.js,
It must be version 1.4.4;
Create a folder img,
Put an loading.gif waiting image inside and put index.html + 4.php + js +img into the www file and run it in the browser


Related articles: