1. axios请求方式
方式1:axios({method:"GET",url:"..."})
方式2:axios({method:"POST",url:"...",data:"..."})
方式3:axios.get("url...")
方式4:axios.post("url...","data...")
2. 安装axios
命令:npm install axios
3. 安装querystring
命令:npm install querystring,
注释:post请求提交数据用
4. 解决跨域访问
vue2.x和vue3.x的vue-cli项目解决案(在文件vue.config.js中追加下记代码)
vue3.2的vite项目解决案(在文件vite.config.ts中追加下记代码)
5. 创建一个后端项目
用于测试处理的ajax请求
package releaseTest.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import releaseTest.entity.User;
/**
* Servlet implementation class AxiosTest
*/
@WebServlet("/AxiosTest")
public class AxiosTest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public AxiosTest() {
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
PrintWriter writer = response.getWriter();
writer.write("{name:'张三'");
writer.write(",id:"+id);
writer.write(",age:18}");
writer.flush();
writer.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String type = request.getParameter("type");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("type:"+type);
System.out.println("name:"+name);
System.out.println("age:"+age);
PrintWriter writer = response.getWriter();
writer.write("{status:'200'");
if("1".equals(type)) {
writer.write(",msg:'ajax普通方案'}");
} else {
writer.write(",msg:'ajax快捷方案'}");
}
writer.flush();
writer.close();
}
}