Making JavaScript call across domains

后端 未结 2 1994
迷失自我
迷失自我 2020-12-22 01:35

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

相关标签:
2条回答
  • 2020-12-22 02:13

    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/

    0 讨论(0)
  • 2020-12-22 02:17

    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

    0 讨论(0)
提交回复
热议问题