jquery ajax跨域访问springmvc后台

jsonp方式访问,后台为springmvc,成功访问后返回一直error,确定前后台代码无问题后。

$.ajax({
 url: 'http://localhost:8080/iCare/test/jsonp',
 type: 'get',
 dataType:'jsonp',
 jsonp: "callback",
 jsonpCallback:"success",
 success:function(data){
  console.log(data.msg);
 },
 error:function(data){
  console.log("error");
  console.log(data);
 }
});
@RequestMapping("jsonp")
@ResponseBody
public String jsonp(String callback) {
	String result = "{msg:\"测试\"}";
	result = callback + "(" + result + ")";
	return result;
}
项目是之前搭建的,配置了   < mvc:message-converters   register-defaults = "true" >   

注入了com.fasterxml.jackson.databind.ObjectMapper自动转换json,所以返回的字符串应该被转换了无法返回。

后台改用PrintWriter方式返回,问题解决,在此记录一下。

@RequestMapping("jsonp")
public void jsonp(String callback,HttpServletResponse response) {
 response.setContentType("text/html;charset=utf-8");  
 PrintWriter wirter;
 try {
  wirter = response.getWriter();
  String result = "{msg:\"测试\"}";
  result = callback + "(" + result + ")";
  wirter.write(result);
 } catch (IOException e) {
  e.printStackTrace();
 }
}



猜你喜欢

转载自blog.csdn.net/cyy298/article/details/79171839
今日推荐