异步请求在项目中也会经常用到,容易忘记,记录一下。
简单示例
Javascript
var curWwwPath = window.document.location.href;var pathName = window.document.location.pathname;var pos = curWwwPath.indexOf(pathName);var localhostPaht = curWwwPath.substring(0, pos);var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);var prefix = localhostPaht + projectName; var postData = ""; $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", url: prefix + "/skyline/saveMj", async: false, data: postData, success: function (data) { return data; }, error: function () { alert("系统错误"); } });
后端代码
@RequestMapping(value = "saveMj") public void saveMj(@RequestBody String data, HttpServletRequest request, HttpServletResponse response,Model model) throws IOException { System.out.println(data); response.setContentType("text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); String mess = "保存成功"; pw.write(URLDecoder.decode(mess, "utf-8")); pw.flush(); pw.close(); }
说明
- 前端数据封装为postData变量提交到后台,也可以将参数采用get的方法附在链接上,后台根据名称获取;
- 后台获取ajax提交的数据默认名称为data,如果数据为json格式,可以进行转换并解析;
- ajax提交后,在后台不需要进行跳转,通过response返回数据,write写入需要返回的数据;
- 前端ajax请求成功后,获取后端返回的数据名称为data,请自行解析;