从备用域名访问时 JavaScript XMLHttpRequest 中断
我有两个指向我网站的域名:nathannifong.com 和 uncc.ath.cx。 站点上的 Javascript 有时需要使用 XMLHttpRequest 获取资源。客户端脚本中的所有资源 URL 均指向 nathannifong.com,当用户通过 uncc.ath.cx 访问该站点时,由于 JavaScript 中的跨域安全策略,脚本会失败。
我应该更改什么以便用户可以通过任何域名访问该站点,但 XMLHttpRequests 仍然有效?
I have two domain names that point to my website, nathannifong.com, and uncc.ath.cx.
Javascript on the site occasionally needs to pull down resources with XMLHttpRequest. All URLs of resources in client scripts refer to nathannifong.com, and when a user comes to the site by uncc.ath.cx, the scripts fail because of cross domain secuity policy in JavaScript.
What should I change so that users can come to the site by any domain name, but the XMLHttpRequests still work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在 URL 中使用域名来发出 ajax 请求,请将其删除,这样域名就会自动映射到用户正在使用的域名,并且您不会遇到跨域问题。
If you are using the Domain Name in the URL's to make a ajax request, remove it hence the domain is automatically mapped to the one the user is using and you will not have the cross domain issues.
xhr 受到 同源策略 的限制,并且无法跨域工作 - 为此,请使用 jsonp提及。
xhr is contrained by the same origin policy and will not work cross domain - for that use jsonp as already mentioned.
根据 CodeProject 的说法,JSONP 将是实现这一目标的一种方法。不过,我自己没有使用过它,但可能值得一看。
According to The CodeProject, JSONP would be a way of accomplishing this. I've not used it myself, however, but it might be worth taking a look there.
您可以查看
window.location
来确定页面的域,然后使用它来加载请求?这样您就可以确保请求发送到正确的域。您还可以查看 JSONP,但仅限于 GET 请求。You could look at
window.location
to determine the page's domain, and then use that to load the request? That way you'd be sure that the request was going to the right domain. You could also look into JSONP, but only for GET requests.