IE alternative to window.stop() (cancel all pendin

2019-03-25 14:54发布

I'm looking for an alternative to window.stop() for IE. I have tried document.execCommand('Stop'), but it doesn't seem to work. I'm trying to cancel a XMLHttpRequest which is called from within a ASP user control i'm using. I can't use jQuery's .abort() since i do not set the request my self.

3条回答
贼婆χ
2楼-- · 2019-03-25 15:27

I assume control on the page uses jQuery.ajax and you know when you need to abort the request, under your criteria.

How about something like this?

(function ($) {
    var xhr = null, 
        originalAjax = $.ajax,
        updatedAjax = function (url, options) {
            xhr = originalAjax(url, options);
        };
    $.ajax = updatedAjax;
})(jQuery);

Now you have a variable called xhr which holds the underlying xmlhttp object. You can call abort() on the object when you need to.

The draw back is that variable will be populated for each ajax request done by jQuery, and I would only include this script on that particular page, maybe even reset the ajax when you are done.

I haven't tried this, just an idea, as I have been mocking ajax calls all the time. Some might think that this approach is a little bit drastic!

Hope you find it useful.

查看更多
Emotional °昔
3楼-- · 2019-03-25 15:33

I understand you don't set the request yourself, but do you have any kind of access to it, so that you can use the onreadystatechanged-event in javascript? If so, you can then determine whether or not you have to cancel the event.

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-25 15:54

If you have access to the object you can do it with the object's abort() and onreadystatechange event handler. Here is a working example I tweaked from w3schools

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==2){ xmlhttp.abort();}
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

As you can see, the request text is not loaded because it gets aborted.

查看更多
登录 后发表回答