ajax跨域访问3解

前端之家收集整理的这篇文章主要介绍了ajax跨域访问3解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一,java代码放开,这样前端感受不到跨域的异同

@RequestMapping("/getlefttimes")
@ResponseBody
String getLeftTimes(HttpServletRequest req,HttpServletResponse resp) {
/* 跨域 begin */
resp.setHeader("Access-Control-Allow-Headers","Content-Type");
resp.setHeader("Access-Control-Allow-Origin","*");
resp.setHeader("Access-Control-Allow-Methods","GET");
resp.setHeader("Allow","GET");

二,jsonp的方式,前后端各自改两个小地方(看红字)

①js:

function canDraw(url){
$.ajax({
type:"GET",
url:url+'?callback=?',
dataType:"jsonp",
success:function(data){
var data = eval(data);
var lefttime = data.lefttimes;
alert(lefttime);
}
})
}

②java:

@RequestMapping("/getlefttimes")
@ResponseBody
String getLeftTimes(HttpServletRequest req,HttpServletResponse resp) {
String callBack = req.getParameter("callback");
int leftTimes = 0;
JSONObject json = new JSONObject();
json.put("lefttimes",leftTimes);
json.put("awarddata",awardData);
return callBack + "(" + json.toString() + ")";
}

即可

原文链接:https://www.f2er.com/ajax/162140.html

猜你在找的Ajax相关文章