$(“form”).serialize():生成一个字符串,各参数用&拼接
$(“form”).serializeArray():将参数生成一个拼接对象
案例:
创建登录servlet
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet{
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//response.setHeader("content-type","text/html;charset=utf-8");//以前的html方式返回信息
response.setHeader("content-type","text/json;charset=utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
Map<String,Object> map=new HashMap<>();
if("szl".equals(username)&&"123".equals(password)){
map.push("success",1);
map.push("errMsg","");
}else{
map.push("success",0);
map.push("errMsg","用户名或密码错误");
}
//创建json格式的mapper对象
ObjectMapper mapper=new ObjectMapper();
String json=mapper.writeValueAsString(map);
response.getWriter().write(json);
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
doGet(request,response);
}
HTML页面
<head>
<script type="text/javascript" src="./js/jquery-3.3.1.js"><script>
<script type="text/javascript">
$(funtion(){
//按钮绑定事件
$('#loginBtn').click(function(){
var v=$('form').serialize();
//打印结果:username=szl&password=123
console.log(v);
var vl=$('form').serializeArray();
//打印结果:[object,object],分别是'username':szl和'password':123
console.log(vl);
});
});
</script>
</head>
<body>
<span style="color:red" id="tip"></span>
<form>
用户名:<input type="text" name="username" id="username"><br>
密码:<input type="password" name="password" id="password"><br>
<input type="button" id="loginBtn" value="登录">
</form>
</body>