How to stop the div from loading an HTML page

remove() on id main is called when another external button is clicked. The problem is that the user presses btn1 and quickly presses this external button, deletion is called before the event handler for btn1 . As a result, the popup is loaded after the div is removed. Is there a way in which a load request can be stopped by clicking on an event handler to delete? I tried using jqXHR.abort() when the remove method is called, but this does not work because the removal is called before ajax is even sent.

There are many buttons, such as btn1, that will send ajax requests for loading HTML and several HTMlL files, for example, a.html load some script files, such as a.js , that will be executed. And if the script refers to some variable that was removed in remove() , there will be a TypeError.

 <div id="base"> <div id="main"> <!-- some more HTML elements --> <button id="btn1"></button> </div> <div id ="popup"> </div> </div> <script> var xhr; $("#btn1").on("click", function(){ xhr = $.ajax( url: "a.html", success: function(){ //do something }), type: "GET" }); $("#main").on("remove", function(){ // delete all resources,etc. xhr.abort(); }); </script> 
+6
source share
2 answers

Try using a global variable

 var removed = 0; $('externabutton').click(function(){ $("#main").remove(); removed = 1; }); $("#btn1").on("click", function(){ xhr = $.ajax( url: "a.html", success: function(data){ if (removed == 0 ) { //append the data } else {removed ==0;} }), type: "GET" }); 
+1
source

Since xhr is asynchronous, therefore, we cannot guarantee the completion of xhr before the #main.remove method. Perhaps you can use a flag to control this.

 var isRemoved = false, xhr; $("#btn1").on("click", function(){ if(isRemoved) return; xhr = $.ajax({ url: "a.html", success: function(){ //do something if(isRemoved) return; }, type: "GET" }); }); $("#main").on("remove", function(){ isRemoved = true; xhr && xhr.abort(); }); 
0
source

All Articles