AJAX

107 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

AJAX

概念:AJAX(Asynchronous JavaScript And XML):异步的JavaScript和XML

AJAX作用: 1.与服务器进行数据交换:通过AJAX可以给服务器发送请求,并获取服务器响应的数据 - 使用了AJAX和服务器进行通信,就可以使用HTML+AJAX来替换JSP页面了

2.异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用 户名是否可用校验,等等.

image.png

同步和异步

image.png

AJAX快速入门

image.png

案例:使用AJAX验证用户名是否存在

需求:在完成用户注册时,当用户名输入框失去焦点时,校验用户名是否在数据库已存在

image.png 前端

//1. 给用户名输入框绑定 失去焦点事件
document.getElementById("username").onblur = function () {
    //2. 发送ajax请求
    // 获取用户名的值
    var username = this.value;

    //2.1. 创建核心对象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2.2. 发送请求
    xhttp.open("GET", "http://localhost:8080/1/selectUserServlet?username="+username);
    xhttp.send();

    //2.3. 获取响应
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            //alert(this.responseText);
            //判断
            if(this.responseText == "true"){
                //用户名存在,显示提示信息
                document.getElementById("username_err").style.display = '';
            }else {
                //用户名不存在 ,清楚提示信息
                document.getElementById("username_err").style.display = 'none';
            }
        }

后端

public class SelectUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收用户名
        String username = req.getParameter("username");
        //2.调用service查询User对象
        boolean flag = true;
        //3.响应标记
        resp.getWriter().write(""+flag);
    }

异步框架

Axios是对原生的AJAX进行封装,简化书写

Axios快速入门

image.png 在这里POST方式和GET方式又体现出了不同,数据的封装不同

get直接在url后加入username

而post是单独列个data出来存放username的值

get的前端代码中

<script src="js/axios-0.18.0.js">
    //1.get
axios({
        method:"get",
        url:"http://localhost:8080/1/axiosServlet?username=zhangsan"
}).then(function (resp){
    alert(resp.data);
})
</script>
</body>
</html>

后端代码中

@WebServlet("/axiosServlet")
public class AXIOS extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get...");
        //1.接收请求参数
        String username = req.getParameter("username");
        System.out.println(username);
        //2.响应数据
        resp.getWriter().write("hello ajax");
    }

Axios请求方式别名

image.png

image.png Axios请求方式别名简化下的代码

//get
axios.get("http://localhost:8080/1/axiosServlet?username=zhangsan").then(function (resp) {
    alert(resp.data);
    
})
//post
axios.post("http://localhost:8080/1/axiosServlet","username=zhangsan").then(function (resp) {
    alert(resp.data);

与上上的代码块中相同

JSON

JavaScript Object Notation:JavaScript对象表示法

由于其语法简单,层次结构鲜明,现多用于作为数据载体,在网络中进行数据传输

JSON基本语法

image.png 通过变量.属性就可以获取到对应的value值

JSON数据与java对象转换

请求数据:JSON字符串转为Java对象

响应数据:Java对象转为JSON字符串

看起来很难,其实使用Fastjson库就能轻易的完成

Fastjson是阿里巴巴提供的一个Java语言编写的高性能功能完善的JSON库,是目前Java语言中最快的JSON库,可以实现Java对象和JSON字符串的相互转换。

image.png

public static void main(String[] args) {
    //1.将java对象转成json对象
    User user = new User();
    user.setId(1);
    user.setUsername("小卡斯蒂");
    user.setPassword("z15788901");
    String jsonStr = JSON.toJSONString(user);
    System.out.println(jsonStr);

    //2.将json对象转成java对象
    User jsonObject = JSON.parseObject(jsonStr,User.class);
    System.out.println(jsonObject);
}

案例

查询所有

image.png 前端

//1. 当页面加载完成后,发送ajax请求
window.onload = function () {
    //2. 发送ajax请求
    axios({
        method:"get",
        url:"http://localhost:8080/brand-demo/selectAllServlet"
    }).then(function (resp) {
        //获取数据
        let brands = resp.data;
        let tableData = " <tr>\n" +
            "        <th>序号</th>\n" +
            "        <th>品牌名称</th>\n" +
            "        <th>企业名称</th>\n" +
            "        <th>排序</th>\n" +
            "        <th>品牌介绍</th>\n" +
            "        <th>状态</th>\n" +
            "        <th>操作</th>\n" +
            "    </tr>";

        for (let i = 0; i < brands.length ; i++) {
            let brand = brands[i];

            tableData += "\n" +
                "    <tr align=\"center\">\n" +
                "        <td>"+(i+1)+"</td>\n" +
                "        <td>"+brand.brandName+"</td>\n" +
                "        <td>"+brand.companyName+"</td>\n" +
                "        <td>"+brand.ordered+"</td>\n" +
                "        <td>"+brand.description+"</td>\n" +
                "        <td>"+brand.status+"</td>\n" +
                "\n" +
                "        <td><a href=\"#\">修改</a> <a href=\"#\">删除</a></td>\n" +
                "    </tr>";
        }

        // 设置表格数据
        document.getElementById("brandTable").innerHTML = tableData;

后端

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1. 调用Service查询
    List<Brand> brands = brandService.selectAll();

    //2. 将集合转换为JSON数据   序列化
    String jsonString = JSON.toJSONString(brands);

    //3. 响应数据
    response.setContentType("text/json;charset=utf-8");
    response.getWriter().write(jsonString);
}

新增品牌

image.png 细节问题: String brandName = request.getParameter("brandName");

上述方式无法接收json数据

前端

<script>
    //1. 给按钮绑定单击事件
    document.getElementById("btn").onclick = function () {
        // 将表单数据转为json
        var formData = {
            brandName:"",
            companyName:"",
            ordered:"",
            description:"",
            status:"",
        };
        // 获取表单数据
        let brandName = document.getElementById("brandName").value;
        // 设置数据
        formData.brandName = brandName;

        // 获取表单数据
        let companyName = document.getElementById("companyName").value;
        // 设置数据
        formData.companyName = companyName;

        // 获取表单数据
        let ordered = document.getElementById("ordered").value;
        // 设置数据
        formData.ordered = ordered;

        // 获取表单数据
        let description = document.getElementById("description").value;
        // 设置数据
        formData.description = description;

        let status = document.getElementsByName("status");
        for (let i = 0; i < status.length; i++) {
            if(status[i].checked){
                //
                formData.status = status[i].value ;
            }
        }

        console.log(formData);
        //2. 发送ajax请求
        axios({
            method:"post",
            url:"http://localhost:8080/brand-demo/addServlet",
            data:formData
        }).then(function (resp) {
            // 判断响应数据是否为 success
            if(resp.data == "success"){
                location.href = "http://localhost:8080/brand-demo/brand.html";
            }
        })

后端

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //1. 接收数据,request.getParameter 不能接收json的数据
   /* String brandName = request.getParameter("brandName");
    System.out.println(brandName);*/

    // 获取请求体数据
    BufferedReader br = request.getReader();
    String params = br.readLine();

    // 将JSON字符串转为Java对象
    Brand brand = JSON.parseObject(params, Brand.class);


    //2. 调用service 添加
    brandService.add(brand);

    //3. 响应成功标识
    response.getWriter().write("success");
}

后续可以使用VUE框架解决前端代码冗余的问题