---------------------------------------------------------
Tomcat服务器处理跨域:(服务器端解决的话,就无需考虑js)
(原文应该来自老外那里,能找到原文的话,恳请告之,谢谢)
1. 将cors-filter-2.1.jar, java-property-utils-1.9.jar 添加到服务器lib下
(下载地址: http://repo.spring.io/libs-snapshot/com/thetransactioncompany/);
(下载地址: http://repo.spring.io/libs-snapshot/com/thetransactioncompany/);
2. 添加web.xml配置
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
Example of applying the CORS filter to a single servlet:
<filter-mapping>
<filter-name>CORS</filter-name>
<servlet-name>MyServlet</servlet-name>
</filter-mapping>
And how to apply the CORS filter to all web app URLs:
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
---------------------------------------------------------
插播一条Flash跨域解决方案(未实测):
将 clientaccesspolicy.xml, crossdomain.xml两个文件放到网站根目录,内容如下:
crossdomain.xml
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
clientaccesspolicy.xml
<?xml version="1.0" encoding="UTF-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
具体,每项配置的含义,大家百度就好了, —。—~~
---------------------------------------------------------
Js处理跨域:
服务器返回的json包上一个callback外壳,然后$.ajax加上属性jsonpCallback(注意大小写),值必须和后端的callback的名字一样
下面的例
子:
服务器返回:hello('world')
ajax属性: jsonpCallback: "hello"
$(document).ready(
function() {
$.ajax({
type : "post",
url : "http://localhost:8080/Test/Test?data=hello('world')&t="
+ $.now(),
dataType : "jsonp",
jsonpCallback : 'hello',
success : function(data) {
alert("data:" + data);
}
}
);
});