第一种jsonp
js代码:
function ajaxJsonp() {
$.ajax({
url : 'http://192.168.7.58:8081/hello',
type : "GET",
async : false,
dataType : "jsonp",
jsonpCallback : "jsonpCallback",//
自定义的jsonp回调函数名,默认为jQuery自动生成的随机函数
jsonp : "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为callback)
success : function(data) {
console.log(data);
console.log(data.name);
alert("服务器连接成功 ajax"+data);
},
error : function(data) {
console.log(data);
console.log(data.name);
alert("服务器连接失败 ajax"+data);
}
});
}
java代码:
@RequestMapping("/hello")
@ResponseBody
public String hello(String callback,Http
ServletRequest request, HttpServletResponse response, HttpSession session) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("name", "kevin");
return callback+"("+
JSONObject.fromObject(map).toString()+");";
}
第二种CROS方式
js代码
function test(){
$.ajax({
url : 'http://192.168.7.58:8081/hello',
type : "GET",
// async : false,
success : function(data) {
console.log(data);
var obj=
JSON.parse(data)
console.log(obj.name);
alert("服务器连接成功 ajax"+data);
},
error : function(data) {
console.log(data);
var obj=JSON.parse(data)
console.log(obj.name);
alert("服务器连接失败 ajax"+data);
}
});
}
java代码:
@RequestMapping("/hello")
@ResponseBody
public String hello(String callback,HttpServletRequest request, HttpServletResponse response, HttpSession session) {
response.setHeader("Access-Control-Allow-Origin", "*" );
response.setHeader("Access-Control-Allow-Methods","GET,POST");
Map<String, Object> map=new HashMap<String, Object>();
map.put("name", "kevin");
return callback+"("+JSONObject.fromObject(map).toString()+");";
}
或者合起来写java代码:
@RequestMapping("/hello")
@ResponseBody
public String hello(String callback,HttpServletRequest request, HttpServletResponse response, HttpSession session) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("name", "kevin");
if (callback!=null&&callback.trim().length()>0) {
return callback+"("+JSONObject.fromObject(map).toString()+");";
} else {
response.setHeader("Access-Control-Allow-Origin", "*" );
response.setHeader("Access-Control-Allow-Methods","GET,POST");
return JSONObject.fromObject(map).toString();
}
}