Cross domain requests
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 mak开发者_JAVA百科e 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?
I thought that whatever domain the script file was loaded from was able to make requests back to that origin?
No. The origin is always the page not the script.
What am I doing wrong?
Your script is violating the cross-domain restriction by by being served from one domain, but requesting a script on another domain.
What's the right approach?
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.
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).
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 to mydomain.com
.
精彩评论