跨域请求
我有一个从 mydomain.com
加载的脚本文件,它向该域发出 ajax 请求。不过,该脚本被加载到其他一些域上,该域对其进行初始化,然后告诉它何时发出请求。但我遇到了问题,因为浏览器认为这是跨域请求。我认为无论从哪个域加载脚本文件都能够向该源发出请求?以下是一些代码作为示例:
someotherdomain.com
的页面:
<html>
<head>
<script type="text/javascript" src="http://mydomain.com/test.js"></script>
<title>Cross-Domain Ajax Test</title>
</head>
<body>
<h1>Test</h1>
<p id="ajax-response"></p>
<script type="text/javascript">
Test.testAjax();
</script>
</body>
</html>
从 mydomain.com
加载的脚本
Test = {
testAjax: function() {
//make ajax request to http://mydomain.com/myendpoint
}
}
我做错了什么?正确的做法是什么?
I have a script file loaded from mydomain.com
that makes ajax requests to that domain. The script though is loaded on some other domain which initializes it and then tells it when to make the requests. I'm running into issues though because the browser is thinks it's a cross domain request. I thought that whatever domain the script file was loaded from was able to make requests back to that origin? Here's some code as an example:
Page at someotherdomain.com
:
<html>
<head>
<script type="text/javascript" src="http://mydomain.com/test.js"></script>
<title>Cross-Domain Ajax Test</title>
</head>
<body>
<h1>Test</h1>
<p id="ajax-response"></p>
<script type="text/javascript">
Test.testAjax();
</script>
</body>
</html>
Script loaded from mydomain.com
Test = {
testAjax: function() {
//make ajax request to http://mydomain.com/myendpoint
}
}
What am I doing wrong? What's the right approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。来源始终是页面,而不是脚本。
No. The origin is always the page not the script.
您的脚本从一个域提供服务,但请求另一域上的脚本,从而违反了跨域限制。
有两种可能:
将运行脚本和调用脚本放在同一个域下。
使用
dataType = "jsonp"
绕过限制。 jQuery 将执行一些魔法(用格式的内联脚本引用替换调用来完成此操作。
Your script is violating the cross-domain restriction by by being served from one domain, but requesting a script on another domain.
There are two possibilites:
Place both the running script and the called script under the same domain.
Use
dataType = "jsonp"
to bypass the restriction. jQuery will perform some magic (replacing the call with an inline script reference in the format of<script src="mydomain.com/endpoint" />
to make this work.脚本的来源始终是
mydomain.com
!您可以使用 Ajax 代理(通过后端)或最终 JSONP 是您的选择(更有可能两者兼而有之,取决于您的需求)。The origin of the script will always be
mydomain.com
! You could either make use of an Ajax Proxy (through your backend) or eventually JSONP is your way to go (more likely both, depends on your needs).当您加载 javascript 时,就好像代码位于
someotherdomain.com
上,并且从该域到mydomain.com
时您将遇到跨域问题。When you load the javascript it is as if the code is on
someotherdomain.com
and you will have cross-domain issues going from that domain tomydomain.com
.