making json/jsonp xhr requests on the file: protocol

微笑、不失礼 提交于 2019-12-04 13:49:50

This is kind of a hatchet job, but it will get you your dynamic callbacks. Basically it counts on the fact that file: transfers will be pretty fast. It sets up a queue of requests and sends them out one at a time. That was the only way I could figure out to make sure that the correct response and callback could be linked (in a guaranteed order). Hopefully someone can come up with a better way, but without being able to dynamically generate the responses, this is the best I can do.

var JSONP = {
  queue: [],
  load: function(file, callback, scope) {
      var head = document.getElementsByTagName('head')[0];
      var script = document.createElement('script');
      script.type = "text/javascript";
      script.src = file;
      head.appendChild(script);
  },

  request: function(file, callback, scope) {
      this.queue.push(arguments);
      if (this.queue.length == 1) {
          this.next();
      }
  },

  response: function(json) {
      var requestArgs = this.queue.shift();
      var file = requestArgs[0];
      var callback = requestArgs[1];
      var scope = requestArgs[2] || this;
      callback.call(scope, json, file);

      this.next();
  },

  next: function() {
      if (this.queue.length) {
          var nextArgs = this.queue[0];
          this.load.apply(this, nextArgs);
      }
  }

};

This is what I did to test

window.onload = function() {
  JSONP.request('data.js', function(json, file) { alert("1 " + json.message); });
  JSONP.request('data.js', function(json, file) { alert("2 " + json.message); });
}

Data.js

JSONP.response({
  message: 'hello'
});

Chrome has very tight restrictions on making ajax calls from a file:// url, for security reasons. They know it breaks apps that run locally, and there's been a lot of debate about alternatives, but that's how it stands today.

Ajax works fine from file urls in Firefox, just be aware that the return code is not an http status code; i.e., 0 is success, not 200-299 + 304.

IE handles these security concerns differently from both Chrome and Firefox, and I'd expect other browsers to each have their own approaches. The border between web and desktop apps is very problematic territory.

"When I try normal XHR requests they fail because of the same origin policy afaict"

...no, I think they fail because a XHR request uses HTTP or HTTPs to request a resource on a web server. (see http://en.wikipedia.org/wiki/XMLHttpRequest).

Unless you're contacting a web server, you can't (successfully) make XHR requests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!