XmlHttpRequest.onload not called

前端 未结 3 1981
星月不相逢
星月不相逢 2021-02-20 10:39

I\'m playing around with this XmlHttpRequest thing. In some tutorials and books, it is the onload function the one that is called when the request is d

相关标签:
3条回答
  • 2021-02-20 11:09

    The onload handler won't be called for yet another reason, I'm adding it here just so it can be helpful to someone else referencing this page.

    If the HTTP response is malformed, the onload handler will not be called either. For example, a plaintext response of 10 bytes that advertises a length of 14 in Content-Length header will not invoke the onload handler. I wasted hours on client code before I start to replace back-end units with test stubs.

    0 讨论(0)
  • 2021-02-20 11:14

    It looks like it was indeed a XSS issue and Firefox was blocking the onload call. I can't still understand why the http network request was actually being done and the onreadystatechange was being called with the DONE readyState.

    I changed the URL to another one in the same domain, and now it works in Firefox (after some cache-related false attempts) and in Chrome. It still does not work in IE8, despite the official docs say it is supported. I've found this SO answer which states otherwise. It looks like the onload function is a more modern convenience method and the old way of checking the result is using onreadystatechange instead.

    I guess I'll accept this answer as the solution unless a more detailed answer is provided.

    0 讨论(0)
  • 2021-02-20 11:19

    IE has different method to create xmlhttprequest.

    function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
    
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.open(method, url, true);
    
      } else if (typeof XDomainRequest != "undefined") {
    
        // Otherwise, check if XDomainRequest.
        // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    
      } else {
    
        // Otherwise, CORS is not supported by the browser.
        xhr = null;
    
      }
      return xhr;
    };
    

    same this article:https://www.html5rocks.com/en/tutorials/cors/

    0 讨论(0)
提交回复
热议问题