使用Fetch发送GET请求
GET请求要传递参数的话,直接在URL后面跟上请求参数即可,如下可以通过循环进行拼接传递
new Vue({
el: "#app",
data: {
formObj: {
logName: '',
logPwd: '',
relName: ''
}
},
methods: {
registerHandler() {
//发送异步请求获取数据
let params = Object.keys(this.formObj).map(key=>key.concat("=").concat(this.formObj[key])).join("&");
fetch(`/register?${params}`).then(resp => resp.json()).then(data => {
console.log(data);
})
}
}
});
Servlet后端接收数据
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求的字符编码,防止中文乱码
request.setCharacterEncoding("utf-8");
// 获取前端传递的数据,通过 name 获取
String logName = request.getParameter("logName");
String logPwd = request.getParameter("logPwd");
String relName = request.getParameter("relName");
}
使用Fetch发送POST请求
POST请求需要进行Header设置,指定请求类型
new Vue({
el: "#app",
data: {
formObj: {
logName: '',
logPwd: '',
relName: ''
}
},
methods: {
registerHandler() {
//发送异步请求获取数据
fetch('/register', {
method: 'POST',
body: JSON.stringify(this.formObj),
headers: {
'content-type': 'application/json'
}
}).then(resp => resp.json()).then(data => {
console.log(data);
})
}
}
});
Servlet后端接收数据
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求的字符编码,防止中文乱码
request.setCharacterEncoding("utf-8");
// 使用字符流进行数据读取,request.getParameter 无法直接获取到数据
BufferedReader reader = request.getReader();
String data = reader.readLine();
JSONObject jsonObject = JSON.parseObject(data);
String logName = jsonObject.get("logName").toString();
String logPwd = jsonObject.get("logPwd").toString();
String relName = jsonObject.get("relName").toString();
}