Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

iframe - Making JavaScript call across domains

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...