直接上代码
// 这里直接定义一个input 按钮即可
<script>
function fun1(){
$.ajax({
type : "POST",
async : false,
url : "http://127.0.0.1:8080/demo",
dataType : "jsonp",
jsonp : "callback", //服务端用于接收callback调用的function名的参数 通过动态创建script标签,添加src属性,前端通过传一个callback给后台,后台返回函数调用,前台将返回的函数调用再进行解析
success : function(data) {
alert(data["demo"]);
},
error : function() {
alert('fail');
}
});
}
</script>
java代码
@RequestMapping("demo")
@ResponseBody
// callback 为接受ajax 回调函数
public void getDemo(HttpServletRequest request,HttpServletResponse response,@RequestParam("callback") String callback) throws IOException {
JSONObject json = new JSONObject();
System.out.println("1111111111111");
// Map<String,Object> map = new HashMap<String,Object>();
json.put("demo", "前后端分离调用成功");
// 这里将返回数据封装成字符串 返回给前端
String str = callback + "("+json.toString() +")";
// 没有指定格式前端容易出现乱码
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(str);
writer.close();
}