一,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