jquery实现的ajax
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-3.3.1/jquery-3.3.1.js" ></script> <script type="text/javascript"> function pp(){ var name=$("#pp").val(); alert(name); $.ajax({ url:"ajax1", type:"POST", dataType: 'json', data:{name:name,age:12,sex:"man",address:"beijing"}, // data:$("#formId").serialize() success:function(data){ alert(data) }, //=================== error============ error: function (jqXHR, textStatus, err) { // jqXHR: jQuery增强的xhr // textStatus: 请求完成状态 // err: 底层通过throw抛出的异常对象,值与错误类型有关 console.log(err.toString()); }, //=================== complete============ complete: function (jqXHR, textStatus) { // jqXHR: jQuery增强的xhr // textStatus: 请求完成状态 success | error console.log('statusCode: %d, statusText: %s', jqXHR.status, jqXHR.statusText); console.log('textStatus: %s', textStatus); }, //=================== statusCode============ statusCode: { '403': function (jqXHR, textStatus, err) { console.log(arguments); //注意:后端模拟errror方式:HttpResponse.status_code=500 }, '400': function () { } } }) } </script> </head> <body> p:<input type="text" name="p" id="pp"/> <input type="button" onclick="pp()" value="cl"/> </body> </html>
后端使用
RequestParam或者pojo接受
@RequestMapping(value = "ajax1",method = RequestMethod.POST) @ResponseBody public String ajax1(ajax_pojo aj // @RequestParam("name")String name, // @RequestParam("age")Integer age, // @RequestParam("sex")String sex, // @RequestParam("address")String address ){ if(aj.getName().equals("zs")){ return "true"; } return "false"; }