Making JavaScript call across domains

2019-01-29 01:33发布

问题:

Here's the goal:

Hand off a script tag that references a JavaScript file on a remote server. That JavaScript file should return HTML that will then be displayed on the calling HTML page.

I've attempted to approach this in two ways:

First, I attempted to use XMLHttpRequest in JavaScript to call this remote server. In IE, it would work as expected but FF, Safari, and Chrome would return an empty response. The overall response I got from my research was that the request was being blocked since the server it's trying to access is different from where it's running (both localhost, but different ports).

Second, I looked at how things like Google Gadgets work as they effectively give you a simple script tag that's referencing external JavaScript. From what I can gather, it appears that there's some sort of iframe action going on simply by the base url being used (example below). This appears to be the way to go, even though using an iframe wasn't my initial thought. I'm guessing the Google code is returning an iframe as HTML to the HTML file that has this script embedded.

Any suggestion on how I should proceed?

<script src="http://www.gmodules.com/ig/ifr?url=http://ralph.feedback.googlepages.com/googlecalendarviewer.xml&amp;synd=open&amp;w=320&amp;h=200&amp;title=&amp;border=%23ffffff%7C3px%2C1px+solid+%23999999&amp;output=js"></script>

回答1:

JSONP is a very common way to deal with same origin policy. Since most javascript frameworks (e.g., jquery) already support it, you don't have to get into technical details to use it.
You can also do the trick yourself by constructing script tag from javascript (as you mentioned). Google Analytics code snippet is an example of such approach:

      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = 'url here';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);

As for iframe idea (if I understand you currectly), it's not gonna work. You can use iframe element on your page to display content from another server, but browser won't let you access it from main page using javascript.

edit
This original proposal details JSONP usage:
http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/



回答2:

You will need a server-side proxy for x-domain calls.

There are many implementations available online or you could probably whip one up in language of your choice to fit into your stack.

More info with graphics and a PHP proxy available here - http://developer.yahoo.com/javascript/howto-proxy.html