一、跨域問題的來源
瀏覽器跨域處理原由:瀏覽器安全防護的“同源政策”影響。
關於什麼是“同源政策”,可以看這邊文章,講解比較詳細易懂https://blog.csdn.net/dreamcatcher1314/article/details/78652884
跨域請求的限制主要是針對前端,Java後端發送Http請求是不存在跨域的問題的,所以通過後端發送Http跨域請求也是解決跨域的一種方式。而這裏我會詳細介紹前後端結合的幾種跨域解決方案
二、跨域請求解決方案
1.Jsonp跨域
Jsonp是目前使用比較廣泛的跨域解決方案,瀏覽器兼容比較好,但是隻能支持Get請求方式。
Jsonp的實現原理:在同源政策的影響下,Ajax請求不能直接跨域,但script、iframe、img等html標籤的src屬性是不受同源政策的影響,直接可以跨域請求的。
$.getJSON("http://item.yangguangqicai.com/product_big/deleteAllFoot/"+userId+"?callback=?",function(data){
});
@RequestMapping(value = "/getFootprint/{userId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
@ResponseBody
public String getFootprint(@PathVariable("userId") int userId,
@RequestParam("callback") String callback) {
String backJson;
try {
backJson = prodBigCustomerApi.getFootprint(userId);
} catch (Exception e) {
backJson = "";
logUtil.writeLog("error", "調用獲取商品瀏覽記錄異常", e);
}
return callback + "(" + backJson + ")";
}
$.ajax({
type: "Get",
url: apiHead + "/api/ShoppingCart/?" + Math.random(),
data: parmModel,
dataType: 'jsonp',
success: function (resultflag, textStatus) {
if (parseInt(resultflag) > 0) { //js, 刪除選中的一項
var par=$(obj).parent().parent().parent();
var currprice = parseFloat((productPrice=="")?0:productPrice);
if(productPrice==987123){//價格待議型
currprice=0;
}
var _totalPrice=$("#span_totalprice").text();
var totalprice = parseFloat(_totalPrice) - currprice*parseFloat(quantity);
if($(obj).parents("table").find("tr").length==1){
clearCart1();
}else{
par.remove();
var rowcount = parseInt($("#cartProductCount").text()) - 1; //重新計算數量
$("#cartProductCount").text(rowcount);
$("#span_count").text(rowcount);
$("#span_totalprice").text("¥"+totalprice.toFixed(2)); //重新算總價
}
}
//刷新上方購物車
//reloadCart();
reloadRightCart();
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
}
});
2.Cross
$.ajax({
type: "POST",
url: "http://item.yangguangqicai.com/test/test",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(data){
console.info(data);
},
error:function(){
}
})
@RequestMapping("test")
@ResponseBody
public String test(HttpServletRequest request,
HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin", "http://a.easypnp.com");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,Access,X-Requested-With,my-http-header");
return "test";
}