ajax datatype_Java解决Ajax跨域解决方案

6090db50cbeb47869a7b8865b4139f1b

一、跨域问题的来源

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

关于什么是“同源政策”,可以看这边文章,讲解比较详细易懂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){});
fb1241dba2f34f24baf3b753db4a0365
@RequestMapping(value = "/getFootprint/{userId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")@ResponseBodypublic 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 + ")";}
fb1241dba2f34f24baf3b753db4a0365
    $.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) {        }    });
fb1241dba2f34f24baf3b753db4a0365

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(){    }}) 
fb1241dba2f34f24baf3b753db4a0365
@RequestMapping("test")@ResponseBodypublic 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";}
fb1241dba2f34f24baf3b753db4a0365
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值