Creating json / jsonp xhr requests in a file: protocol

I am writing a javascript application that will be hosted by protocol file:(i.e. an application is just a html, css and javascript folder sitting somewhere on my hard drive). When I try regular XHR requests, they fail due to the same affinity policy of origin.

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

Note. So far I have all jsonp files using hard-coded callback functions, but I would like to use dynamic callback functions for these requests .. is there any way to do this?

+3
source share
3 answers

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

Data.js

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

Chrome ajax- ://url, . , , , , .

Ajax URL- Firefox, , http; 0 - , 200-299 + 304.

IE - Chrome, Firefox, , . - .

+1

" XHR, - "

... , , , XHR- HTTP HTTP -. (. http://en.wikipedia.org/wiki/XMLHttpRequest).

If you do not contact the web server, you cannot (successfully) make XHR requests.

-2
source

Source: https://habr.com/ru/post/1783318/


All Articles