Resolve jQuery ajax request interruption in IE6

  • 2021-06-29 06:21:22
  • OfStack

Scenario Restore: An click event is bound to the a tag to trigger an ajax request. In IE6, requests are often interrupted, and in non-IE6 everything works.


<a href="javascript:;" id="btn">click me</a>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
 var url = "http://api.flickr.com/services/"
 "feeds/photos_public.gne?tags=car&"
 "tagmode=any&format=json&jsoncallback=?";
 $( "#btn" ).click(function(){
  $.getJSON( url, function( data ){
   alert( data );
  });
 });
</script>

Using Fiddler2 to monitor requests in IE6, there is often "aborted", which has been tossing around for a long time and is quite bizarre.Later, the a tag was replaced with button, and the request was normal. Finally, it was reminded that the request was interrupted by the default event of the a tag.However, in the HTML code, the href tag of the a has been set to "javascript:;".Usually this prevents default events (page jumps).The click event of the a tag executes before the href jump is executed, which happens if href is an javascript statement.IE6 interrupted an ajax request triggered by click while executing the javascript statement of href.Use href="javascript:;"To prevent default events, moving the action that prevents default events to the click event solves the problem so that the javascript statement in href is not executed.


$( "#btn" ).click(function(e){
 $.getJSON( url, function( data ){
  alert( data );
 });
 e.preventDefault();
});

Note: e.preventDefault();The purpose of this sentence is to prevent default events in js.


Related articles: