ajax跨域,携带cookie

解决方案很简单。

直接上代码:


web.xml中:

添加了 cors来解决跨域

(奇怪的是,credentials设置为false。反正这个是照搬的。。。)

  <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
      <param-name>cors.allowed.origins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>cors.support.credentials</param-name>
      <param-value>false</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


或者在代码中设置:

response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST");
		response.setHeader("Access-Control-Allow-Credentials", "true");

ajax:

$.ajax({  
                type: "post",  
                url: "Get",
                crossDomain: true,                 //加这二行支持ajax跨域,允许跨域
                xhrFields: {withCredentials: true},//加这二行支持ajax跨域,携带凭证   
                success: function (data) {  
                    alert(data);  
  
                }  
            });





posted @ 2017-10-16 16:35  正怒月神  阅读(707)  评论(0编辑  收藏  举报