网页解决跨域问题

1、后台

//预警值
@RequestMapping("/selectT")
//String callback 这个值需要跟页面的jsonp的值对应
void selectT(HttpServletResponse response, String callback) throws IOException {
//设置编码保证前端收到的中文不是???问号
response.setContentType("text/html;charset=utf-8");
// response.setHeader("Access-Control-Allow-Origin", "jsonp");
thresholdService service = new thresholdServiceImp();
threshold threshold = new threshold();
threshold = service.selectThers(1);
JSONObject jsonObject = new JSONObject();
jsonObject.put("threshold", threshold);
//拼接
response.getWriter().print(callback+"("+jsonObject.toString()+")");

}

2、页面Ajax写法

$.ajax({
type:"get",
url:"http://IP(服务器ip地址)/threshold/selectT",
<!--获取json数据-->
dataType:"JSONP",
jsonp:"callback",
processData: false,
success:function(data){
console.info(data);
$("#fazhi").html(data.threshold.state);
},
error:function(){
alert("数据加载异常!");
}
});

 

3.加注解即可

@CrossOrigin

 

注:以上内容仅供个人学习记录使用,如有与其他博文有冲突,请慎用!

 

posted @ 2019-09-02 15:22  夏天丷  阅读(95)  评论(0编辑  收藏  举报