使用axiox实现post请求:
axios({
method:"post",
url:"http://localhost:8080/hello/test",
data: {
key1: value1,
key2: valeu2
}
})
method:定义请求方法,指定请求方法是post方法
url:定义请求路径,使用完整路径,后面不需要像get请求一样加上键值对来传递参数
data:里面以键值对的形式来定义键值对,不会让敏感信息出现在请求地址中
另一种写法:
axios.post(
'http://localhost:8080/hello/test',
{
key1: value1,
key2: valeu2
})
如何在后端获取到post请求提交的参数:
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String string = reader.readLine();
JSONObject jsonObject = JSONObject.parseObject(string);
String value01 = jsonObject.getString("key1"); //第一个参数
String value02 = jsonObject.getString("key1"); //第二个参数
使用axios实现post请求并从服务端接收数据
使用的axios实现的数据提交:封装在一个js的函数中,并绑定在一个按钮中,提交input中的值到后台的servlet中
function find02() {
axios({
method:"post",
url:"http://localhost:8080/hello/test",
data: {
key1: value1,
key2: valeu2
}
}).then(function (resp){
let a = resp.data;
console.log(a);
})
}
document.getElementById("submit01").addEventListener('click', find02);
另一种写法:
function find03() {
axios.post(
'http://localhost:8080/hello/test',
{
key1: value1,
key2: valeu2
}).then(function (resp){
let a = resp.data;
console.log(a);
})
}
document.getElementById("submit01").addEventListener('click', find02);
后端处理之后将数据返送到前端的方式:
response.setContentType("text/json;charset=utf-8");
String jsonString = JSON.toJSONString(要发往axios中的数据);
response.getWriter().write(jsonString);
- 关于参数的传递,需要使用setContentTyp方法将字符编码格式改为json和utf-8;
- 将在后端获取到的对象集合转化为json字符的形式;
- 将已经转化为json数据类型的数据传递给回调函数
resp作为回调函数的参数,由后端传递而来,里面是一个由数据库获取到的对象集合,利用其中的数据可以在js文件中对前端页面进行修改,实现页面的局部刷新。由与后端的servlet数据已经传输到前端,不需要再将获取到的数据存到request域中去,也不需要再经转发到HTML或者JSP页面进行从新加载。
相关链接:使用axiox实现get请求