This article is currently in the process of being translated into Vietnamese (~16% done).
Aborting an AJAX request
Có những tình huống ta cần bỏ đi một AJAX request trước khi nó kết thúc. Thường khi người dùng thực hiện một hành động bao gồm các AJAX request nào đó nhiều lần trong khoảng thời gian ngắn.
<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" />
<script type="text/javascript">
function PerformSimpleCalculation()
{
$.get("/tests/calc.php", function(data, textStatus)
{
alert(data);
});
}
</script>
It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).
Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:
<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" />
<script type="text/javascript">
var calculationRequest = null;
function PerformAbortableCalculation()
{
if(calculationRequest != null)
calculationRequest.abort();
calculationRequest = $.get("/tests/calc.php", function(data, textStatus)
{
alert(data);
});
}
</script>
We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.