Java解决Ajax跨域请求的方式

一、跨域问题的来源

浏览器跨域处理原由:浏览器安全防护的“同源政策”影响。

关于什么是“同源政策”,可以看这边文章,讲解比较详细易懂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";
	}

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章