解决跨域访问(服务器端、Js端)

---------------------------------------------------------
Tomcat服务器处理跨域:(服务器端解决的话,就无需考虑js)
(原文应该来自老外那里,能找到原文的话,恳请告之,谢谢)
1. 将cors-filter-2.1.jar, java-property-utils-1.9.jar 添加到服务器lib下
(下载地址: 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);
			}
		}
	);
});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值