How to XHR local files?

后端 未结 2 1974
清歌不尽
清歌不尽 2021-01-16 07:01

This fails by giving result of 0 instead of 200. Im sure this has to do with xmlhttprequests being not allowed to access local drive but that should only apply to web scope,

2条回答
  •  离开以前
    2021-01-16 07:25

    XHR for local files will result in status 0. That is normal and doesn't mean there was an error.
    XMLHttpRequest status refers to actual HTTP server response which is not the case in accessing local files, therefore a 0 is passed as status.

    From: How to convert an overlay extension to restartless

    Note: When using XMLHttpRequest to access a file:// URL the request.status is not properly set to 200 to indicate success. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true.

    Update:

    Personally I would use the API and not bother with status

    Example from: Connecting to Remote Content

    let url = "http://www.example.com/";
    let request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                  .createInstance(Components.interfaces.nsIXMLHttpRequest);
    request.onload = function(aEvent) {
      // code to do on success
      //window.alert("Response Text: " + aEvent.target.responseText);
    };
    request.onerror = function(aEvent) {
      // there was a problem, handle error
      //window.alert("Error Status: " + aEvent.target.status);
    };
    request.open("GET", url, true);
    request.send(null);
    

    I use a modified version of above in my own add-ons.

提交回复
热议问题