页面中一个form表单,给submit的input标签绑定一个点击事件,代码如下:
<form method="get" action="/login">
<input type="text" placeholder="请输入用户名" id="username" name="username" required/>
<input type="password" placeholder="请输入密码" id="password" name="password" required/>
<input type="submit" onclick="login()" value="登录" />
</form>
js代码是login函数,获取表单将其序列化,代码:
function login(){
var formData=$("form").serialize();//form对象然后序列化
$.ajax({
type: "POST",
url: "login",
processData:true,
data:formData,
success: function(msg){
window.alert(msg)
}
})
}
后端获取表单提交来的值,代码:
@RequestMapping("/login")
@ResponseBody
public String login(Model model, HttpServletRequest request, HttpServletResponse response){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+":"+password);
return "登录成功";
}