开发者

why my JS can't load document from another server?

I have two web-sites and two files:

provider.com/provide.js
viewer.com/index.html

viewer.com/index.html renders information to the user, and gets this information from provider.com. The file viewer.com/index.html looks like this (jQuery is used):

<script type="text/javascript"
src="http://provider.com/provide.js"></script>
<script type="text/javascript">
  provide(function() { alert('works!'); });
</script>

provider.com/provide.js looks like this (I omit unnecessary details):

function provide(callback)
{
  $.ajax(
    {
      'url': 'http://provider.com/',
    }
  );
}

I'm getting this message in al开发者_运维问答l browsers: Failed to load resource: cancelled.

I have a feeling that I break some security restrictions. Could anyone explain what restrictions, if any. Thanks.


Eventhough the provide.js file is loaded from the provider domtain, it's still loaded in the context of the HTML page, so it's in the viewer domain. When the code tries to make the AJAX call to get information from the provider domain, you run into the cross domain limitation.

You can't use AJAX to load information across domains. However you can use JSONP as data format, then the ajax method will not do an AJAX call, instead it will use a script tag to load the information, which is allowed.


You can't request Javascript to send requests cross domain, for security reasons.

You can however make the request to the server which can retrieve the files and print the results for you, that Javascript can then request.


A brief introduction to the same-origin policy, described in other answers, can be found here:

http://en.wikipedia.org/wiki/Same_origin_policy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜