Day01-Ajax

一.JSON方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <table>
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>

    <script>
        var data = [
            {
                "id": "0001",
                "name": "张三",
                "age": 18,
                "gender": "男"
            },
            {
                "id": "0002",
                "name": "李四",
                "age": 20,
                "gender": "女"
            },
            {
                "id": "0003",
                "name": "王五",
                "age": 18,
                "gender": "男"
            }
        ]

        console.log(data);

        // 将数组对象形式的数据转换为 json 格式
        var dataStr = JSON.stringify(data);
        console.log(dataStr);

        // 将 json 格式的数据转换为数组对象形式
        var data2 = JSON.parse(dataStr);
        console.log(data2);


        var table = document.querySelector("table");
        data2.forEach(function (value, index) {
            table.innerHTML += `<tr>
                                    <td>${value.id}</td>
                                    <td>${value.name}</td>
                                    <td>${value.age}</td>
                                    <td>${value.gender}</td>
                                </tr>`
        })

    </script>

</body>

</html>

二.Ajax使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>

        // 1.创建XMLHttpRequest对象
        var xhr = new XMLHttpRequest();

        // 2.Ajax向服务器发起请求  open("请求方式","请求地址")
        xhr.open("GET", URL);
        xhr.open("POST", URL);

        // 3.设置请求头

        // GET请求不需要设置请求头

        // post请求需要设置请求头
        // 默认格式 (窗体格式)    ?userName=1234&psd=abcd
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // json格式
        xhr.setRequestHeader("Content-Type", "application/json");

        // 4.发送请求
        // get的一般不用send
        xhr.send(null);
        // post方法携带传递信息
        xhr.send(content);
        // name="田鹏鹏"&age=18
        // {"name":"田鹏鹏","age":18}

        // 5.获取响应,监听请求状态的改变
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                console.log("请求完成");

                // 完善的判断信息
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    console.log("请求成功");

                    // 拿到响应信息
                    console.log(xhr.response);
                    // 响应正文
                    console.log(xhr.responseText);

                    // ... 

                    var data = JSON.parse(xhr.responseText);

                    // ... 
                }
            }
        }

        
    </script>

</body>

</html>

三.get请求

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <input type="text"><button class="search">搜索</button><button>添加</button>

    <table border="1" cellspacing="0" cellpadding="10">
        <tr>
            <th>班级</th>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>爱好</th>
            <th>手机号</th>
            <th>地址</th>
            <th>备注</th>
            <th>日期</th>
            <th>操作</th>
        </tr>
    </table>

    <script>

        // 获取table
        var table = document.querySelector("table");
        // 获取搜索框
        var search = document.querySelector("input");
        // 获取搜索按钮
        var sbtn = document.querySelector(".search");

        var data;
        sbtn.onclick = function () {
            if (search.value) {
                data = search.value;
            } else {
                data = "";
            }

            table.innerHTML = `<tr>
                                <th>班级</th>
                                <th>学号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>年龄</th>
                                <th>爱好</th>
                                <th>手机号</th>
                                <th>地址</th>
                                <th>备注</th>
                                <th>日期</th>
                                <th>操作</th>
                            </tr>`;

            // 1.创建 XMLHttpRequest 对象
            var xhr = new XMLHttpRequest();

            // 2.发起请求 open()
            xhr.open("GET", "http://localhost:3008/api/student/getStudent?id=" + data);

            // 3.设置请求头

            // 4.发送请求 send()
            xhr.send();

            // 5.监听状态改变 onreadystatechange()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                        console.log(xhr.responseText);      // json
                        var data = JSON.parse(xhr.responseText);
                        console.log(data);

                        data.forEach(function (value) {
                            table.innerHTML += `<tr>
                                        <td>${value.clazz}</td>
                                        <td>${value.id}</td>
                                        <td>${value.name}</td>
                                        <td>${value.gender}</td>
                                        <td>${value.age}</td>
                                        <td>${value.hobby}</td>
                                        <td>${value.tel}</td>
                                        <td>${value.address}</td>
                                        <td>${value.remark}</td>
                                        <td>${value.date}</td>
                                        <td>
                                            <button>编辑</button>
                                            <button>删除</button>
                                        </td>
                                    </tr>`
                        })
                    }
                }
            }
        }



    </script>

</body>

</html>

四.post请求

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="./05-ajax封装.js"></script>
</head>

<body>

    <script>

        // // 1.创建 XMLHttpRequest 对象
        // var xhr = new XMLHttpRequest();

        // // 2.发起请求 open()
        // xhr.open("POST", "http://localhost:3008/api/student/addStudent");

        // // 3.设置请求头
        // // 窗体格式  "?name='张三'&age=18"
        // // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        // xhr.setRequestHeader("Content-Type", "application/json");

        // // 4.发送请求 send()
        // // 必传参数: clazz班级 name 姓名  gender 性别 age 年龄 tel 电话 address 地址信息 remark 备注信息
        // // var data = "clazz='火花239'&name='丁方园'&age=23&tel=13888888888&address='兰考'&remark='游戏大神'"

        // var data = [
        //     {
        //         calzz: "火花239",
        //         name: "胡定海",
        //         age: 60,
        //         tel: 13666666666,
        //         address: "信阳",
        //         remark: "信阳彭于晏"
        //     }
        // ]
        // xhr.send(JSON.stringify(data));

        // // 5.监听 
        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState === 4) {
        //         if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
        //             console.log(xhr.response);
        //         }
        //     }
        // }

        var data = {
            calzz: "火花239",
            name: "侯志强",
            age: 18,
            tel: 13666666666,
            address: "信阳",
            remark: "信阳彭于晏"
        }
        postData(data, "http://localhost:3008/api/student/addStudent", function (xhr) {
            console.log(xhr.response);
        })

    </script>

</body>

</html>

五.Ajax封装

// 封装get请求
function getData(data, url, fun) {
    // 1.创建对象
    var xhr = new XMLHttpRequest();
    if (!data.includes("=")) {
        data = formData(data);
    }
    url += "?" + data;
    // 2.发起请求
    xhr.open("GET", url);

    // 3.发送请求
    xhr.send();

    // 4.监听状态改变
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                console.log(xhr.responseText);
                fun(xhr);
            }
        }
    }
}


// 数据转换为窗体格式
function formData(data) {
    var arr = [];
    for (var key in data) {
        arr.push(key + "=" + data[key]);
    }
    data = arr.join("&");
    return data;
}


// 封装 post 请求
function postData(data, url, fun) {
    // 1.创建对象
    var xhr = new XMLHttpRequest();
    // 2.发起请求
    xhr.open("POST", url);
    // 设置请求头
    if (data instanceof Object) {
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify(data));
    } else {
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }
    // 4.监听状态改变
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                console.log(xhr.responseText);
                fun(xhr);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值