星期日, 七月 23, 2006
XMLHttpRequest对象实现的安全性考虑:为什么不能跨域访问
AJAX通过XMLHttpRequest对象发送http请求,但是只能访问本站点内的资源,站点A的页面通过此对象访问站点B上的资源的行为是被禁止的。
原因,参考:http://www.w3.org/TR/XMLHttpRequest/#security
The restrictions are there to stop untrusted users of the API from using the implementation to retrieve sensitive data. Specifically, an implementation in a web browser will often want to restrict pages from a website A to retrieve data from website B. The reason for this is that website B could reside inside a corporate firewall. If data could be retrieved from website B then website A could use the browser effectively circumvent the firewall.
假设站点B是一个公司的内网(在防火墙后面),如果允许站点A的某个网页上的XMLHttpRequest对象访问站点B的资源的话,那么,当站点B所在公司的员工访问此页面时,站点A就可以通过脚本获得内网资源,使得防火墙形同虚设。
如果站点A和站点B是一个域名下的两个站点(子域),Abe Fettig’s Weblog介绍了一个方法(iframe+ajax)让XMLHttpRequest对象跨站点访问:How to make XmlHttpRequest calls to another server in your domain