在文件:protocol上发出json / jsonp xhr请求 [英] making json/jsonp xhr requests on the file: protocol

查看:144
本文介绍了在文件:protocol上发出json / jsonp xhr请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a javascript app that will be hosted on a file: protocol (ie: the application is just a folder of html, css, and javascript sitting someplace on my hard drive). When I try normal XHR requests they fail because of the same origin policy afaict.

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

So my question is this, what's the best way to request json/jsonp files with an app as described above?

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

Note: So far I've got all of my jsonp files using a hard-coded callback functions, but I'd like to be able to use dynamic callback functions for these requests.. is there a way to do this?

推荐答案

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

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

};

这就是我测试的方法

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

这篇关于在文件:protocol上发出json / jsonp xhr请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆