文章目录
一、如何使用ajax想后台发送数据
前端,我们使用Ajax发送数据给后台,那么如何发送?其代码如下:
window.checkLogin = function() {
let userName = document.getElementById("userName").value;
let userPass = document.getElementById("userPass").value;
$.ajax({
url: "http://localhost:8080/accountController/checkLogin.do",
type: 'get',
//type后边跟字符串post或者get,默认为get,我们这里使用get是为了开发过程中的Debug
dataType: 'text',
//dataType在开发中一般使用json,这里是用text是发送数据比较方便,如果使用json需要构造json格式的数据
data: {
"userName": userName,
"userPass": userPass,
},
success(data) {
console.log(data);
}, error(e) {
console.log(e);
}
});
}
那么我们这样就可以发送数据给后台的controller。你发送的位置就是url后边跟的路由路径。这里我们的路由可以看出是发送给accountController下的checkLogin.do方法。需要注意的是我们如果使用ajax发送数据的话需要引入jQuery.
二、后台如何接收ajax发送的数据
我们这里使用springMVC进行后台的数据接收,一中说到我们的数据是发送给accountController下的checkLogin.do方法。那么我们的后台一定要有accountController和checkLogin.do,否则的话,ajax发送的路由就会not found.
我们这里可以看下后台代码:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web