最近在做一个有关spring boot的小项目,然后在其中用到了ajax,由于对前端不是很熟练,在刚开始用ajax的时候犯了很多错误,为了防止以后要用到又忘了,故记下以供之后参考。
对于表单,要设置action=“#”,还有onsubmit为return false,阻止表单自身的提交,然后按钮的类型就为普通按钮,并添加onclick事件,代码如下
<form id="form" action="#" method="post" enctype="multipart/form-data" onsubmit="return false">
<input type="text" name="userId" id="userId" required/>
<input type="password"name="password" id="psw" required/>
<button type="button" onclick="login()">登录</button>
</form>
对于上面的表单,ajax代码如下,其中传参,有两种方法,一种是按照我下面的方面,写在data里,另一种是直接拼接url。
function login(){
var userId = document.getElementById(userId).value;
var password = document.getElementById(psw).value;
$.ajax({
type: "post",
dataType: "json",
//方法一
url: "/login",
data: {
userId: userId,
password: password
},
//****************************//
/*方法二*/
//url:"/login?userId="+userId+"&password="+password,
//data:null,
//*****************************//
cache: false,
success: function (result) {
if (result == true) {
alert("true");
} else {
alert("false");
}
},
error: function () {
alert("ajax出现异常");
}
});
}
下面是controller方法
@RequestMapping("/login")
@ResponseBody //这里要注意,如果要返回值得话,要记得加这个注解,这样子才能以json值返回到ajax
public boolean handleLoginByArticleDetail(String userId, String password) {
//数据库操作
return isSuccess;
}
以上仅供参考,有错误可以指出,谢谢。