3

我正在编写一个将托管在file:协议上的 javascript 应用程序(即:该应用程序只是位于我硬盘上某个位置的 html、css 和 javascript 的文件夹)。当我尝试正常的 XHR 请求时,它们会因为相同的源策略而失败。

所以我的问题是,使用上述应用程序请求 json/jsonp 文件的最佳方式是什么?

注意:到目前为止,我的所有 jsonp 文件都使用硬编码的回调函数,但我希望能够对这些请求使用动态回调函数。有没有办法做到这一点?

4

2 回答 2

7

这是一种打手的工作,但它会为您提供动态回调。file:基本上,它依赖于传输速度非常快的事实。它设置了一个请求队列并一次发送一个。这是我能确定的唯一方法,以确保可以链接正确的响应和回调(以保证的顺序)。希望有人能想出更好的方法,但不能动态生成响应,这是我能做的最好的。

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);
      }
  }

};

这就是我所做的测试

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); });
}

数据.js

JSONP.response({
  message: 'hello'
});
于 2011-01-04T13:28:36.473 回答
1

出于安全原因,Chrome 对从 file:// url 进行 ajax 调用有非常严格的限制。他们知道这会破坏在本地运行的应用程序,并且关于替代方案的争论很多,但这就是今天的情况。

Ajax 在 Firefox 中的文件 url 工作正常,请注意返回码不是 http 状态码;即,0 是成功,而不是 200-299 + 304。

IE 处理这些安全问题的方式与 Chrome 和 Firefox 不同,我希望其他浏览器各有自己的方法。Web 和桌面应用程序之间的边界是非常有问题的领域。

于 2011-06-17T14:53:25.030 回答