天天看點

Jquery Ajax解決跨域請求session丢失的問題

後端代碼:

//ajax請求的跨域允許
		resp.setHeader("Access-Control-Allow-Credentials","true"); //是否支援cookie跨域
		resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
           

第二句中必須指定位址,不能用"*"來代替,而且127.0.0.1和localhost之間也算跨域,要注意這個坑

前端代碼:

$.ajax({
				url: "http://localhost:8080/Servlet/MyServlet",
				dataType:"text",
				type:"get",
	            xhrFields: {
	                withCredentials: true
	            },
	            crossDomain: true,
	            success:function(result){
	            	console.log(result)
	            }
			});
           

前端代碼中一定要加上

xhrFields: {

withCredentials: true

},

crossDomain: true,

這兩句話

上一篇: 什麼是JPA

繼續閱讀