Day01-Ajax

一.JSON方法

javascript 复制代码
<!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使用

javascript 复制代码
<!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请求

html 复制代码
<!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请求

html 复制代码
<!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封装

javascript 复制代码
// 封装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);
            }
        }
    }
}
相关推荐
堕落年代7 分钟前
Vue主流的状态保存框架对比
前端·javascript·vue.js
没资格抱怨8 分钟前
el-pagination的使用说明
javascript·vue.js·elementui
OpenTiny社区18 分钟前
TinyVue的DatePicker 组件支持日期面板单独使用啦!
前端·vue.js
冴羽18 分钟前
Svelte 最新中文文档教程(22)—— Svelte 5 迁移指南
前端·javascript·svelte
树上有只程序猿22 分钟前
Vue3组件通信:多个实战场景,轻松玩转复杂数据流!
前端·vue.js
青红光硫化黑27 分钟前
React基础之useEffect
javascript·react.js·ecmascript
剪刀石头布啊30 分钟前
css属性值计算过程
前端·css
bin915334 分钟前
DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加列宽调整功能,示例Table14基础固定表头示例
前端·javascript·vue.js·ecmascript·deepseek
小华同学ai37 分钟前
吊打中文合成!这款开源语音神器效果炸裂,逼真到离谱!
前端·后端·github
二川bro42 分钟前
TensorFlow.js 全面解析:在浏览器中构建机器学习应用
javascript·机器学习·tensorflow