AJAX使用笔记

1、AJAX是什么?AJAX是一种异步的数据交换技术,需要在前端、后端都进行编写代码

使用AJAX之前,需要配置两个文件,一个是axios文件,一个是JSON配置文件

<script src="js/axios-1 0.18.0.js"></script>

其中JSON配置,使用POM.xml中引入

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

2、在后端实现需要定义一个用于接收请求的servlet,如

@WebServlet(name = "AxiosServlet", value = "/AxiosServlet")
public class AxiosServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get....");
String username = request.getParameter("username");
System.out.println(username);
response.getWriter().write("hello axios");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post....");
this.doGet(request, response);
}
}

3、在前端需要引入js文件,发送ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="js/axios-0.18.0.js"></script>
<script>
    axios({
        method:"post",
        url:"http://localhost:8080/brand-demo/AxiosServlet",
        data:"username=zhangsan"
    }).then(function(resp){
        alert(resp.data);
    })
</script>



</body>
</html>

以上只是一个示例

 

posted @ 2022-07-20 10:57  mountain_city_boy  阅读(99)  评论(0)    收藏  举报