AJAX尚硅谷学习笔记(一)

此笔记用于自己随时翻阅,目录结构如下

注意:7-跨域,内容放在第二篇

# HTTP.md


HTTP(hypertext transport protocol)协议【超文本传输协议】,协议详细规定了浏览器和万维网服务器之间互相通信的规则。

## 请求报文
重点是格式和参数
'''
行      GET1/s?ie=utf-8       HTTP/1.1
头      Host: atguigu.com
        Cookie: name=guigu
        Content-text: application/x-www-form-urlencoded
        User-Agent: chrome 83
空行
体      username=admin?password=admin
'''

## 响应报文
'''
行      HTTP/1.1 200 OK
头      Content-Type: text/html;cahrset=utf-8
        Content-length: 2048
        Content-encoding: gzip
空行
体      <html>
            <head></head>
            <body>
                <h1>hhh</h1>
            </body>
        </html>
'''
//express基本使用.js


//1.引入express
const express = require('express');

//2.创建应用对象
const app = express();

//3.创建路由规则
//request是对请求报文的封装;response是对响应报文的封装
app.get('/', (request, response) => {
    //设置响应
    response.send('HELLO EXPRESS');
});

//4.监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动,8000端口监听中....");
})
<!-- 1-GET.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        //获取button元素
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById("result");
        //绑定事件
        btn.onclick = function () {
            //1.创建对象
            const xhr = new XMLHttpRequest();
            //2.初始化 设置请求方法和url
            xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
            //3.发送
            xhr.send();
            // 4.事件绑定 处理服务端返回的结果
            // on when 当。。。时候
            // readystate是xhr对象中的属性,表示状态0 1 2 3 4
            // 0:未初始化 1:open方法调用完毕 2:send方法调用完毕
            // 3:服务端返回了部分结果 4:服务端返回了全部结果
            // change 改变
            xhr.onreadystatechange = function () {
                //判断
                if (xhr.readyState === 4) {
                    //判断响应状态码200 404 403 401 500
                    //2xx 成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //处理结果(行 头 空行 体)
                        //响应
                        // console.log(xhr.status);//状态码
                        // console.log(xhr.statusText);//状态字符串
                        // console.log(xhr.getAllResponseHeaders());//所有响应头
                        // console.log(xhr.response);//响应体

                        //设置result的文本
                        result.innerHTML = xhr.response;
                    } else {

                    }
                }
            }
        }
    </script>

</body>

</html>
<!-- 2-POST.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX POST请求</title>
</head>
<style>
    #result {
        width: 200px;
        height: 100px;
        border: solid 1px #903;
    }
</style>

<body>
    <div id="result"></div>
    <script>
        //获取元素对象
        const result = document.getElementById("result");
        //绑定事件
        result.addEventListener("mousemove", function () {
            // console.log("test");
            //1.创建对象
            const xhr = new XMLHttpRequest();

            //2.初始化 设置类型与URL
            xhr.open('POST', 'http://127.0.0.1:8000/server');
            //设置请求头
            //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            //以下自定义请求头会报错,解决方法:
            //在server.js的响应头中添加response.setHeader('Access-Control-Allow-Headers', '*')
            //并改为app.all
            xhr.setRequestHeader('name','atguigu');

            //3.发送
            xhr.send('a=100&b=200&c=300');
            //xhr.send('a:100&b:200&c:300');
            //xhr.send('234536271');

            //4.事件绑定
            xhr.onreadystatechange = function () {
                //判断
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //处理服务端返回的结果
                        result.innerHTML = xhr.response;
                    }
                }
            }
        });
    </script>

</body>

</html>
<!-- 3-JSON.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON响应</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>

<body>
    <div id="result"></div>
    <script>
        const result = document.getElementById('result');
        //绑定键盘按下事件
        window.onkeydown = function () {
            // console.log("test");
            //发送请求
            const xhr = new XMLHttpRequest();
            //设置响应体数据的类型
            xhr.responseType = 'json';
            //初始化
            xhr.open('GET', 'http://127.0.0.1:8000/json-server');
            //发送
            xhr.send();
            //事件绑定
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log(xhr.response);
                        // result.innerHTML=xhr.response;

                        //如果只想要其中某个数据,方法:
                        //1.手动对数据转化
                        // let data = JSON.parse(xhr.response);
                        // console.log(data);
                        // result.innerHTML = data.name;

                        //2.自动对数据转换(需要设置响应体数据的类型xhr.responseType='json';)
                        console.log(xhr.response);
                        result.innerHTML = xhr.response.name;
                    }

                }
            }
        }
    </script>
</body>

</html>
<!-- 4-IE缓存问题.html -->


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

<!-- IE浏览器会对AJAX请求结果缓存,下次再发送请求时,返回的是本地缓存,而非服务器的最新数据
对于时效性较强的场景,AJAX会影响反映的结果 -->

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IE缓存问题</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.querySelector('#result');
        btn.addEventListener('click', function () {
            //console.log('test');
            const xhr = new XMLHttpRequest();
            xhr.open("GET", 'http://127.0.0.1:8000/ie?t=' + Date.now());
            //Date.now()获取当前的时间戳
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //处理服务端返回的结果
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>

</html>
<!-- 5-超时与网络异常.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>请求超时与网络异常</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.querySelector('#result');
        btn.addEventListener('click', function () {
            //console.log('test');
            const xhr = new XMLHttpRequest();

            //2s超时设置
            xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function () {
                alert("网络异常,请稍后重试!");
            }
            //网络异常回调
            xhr.onerror = function () {
                alert("你的网络有问题");
            }

            xhr.open("GET", 'http://127.0.0.1:8000/delay');
            //Date.now()获取当前的时间戳
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //处理服务端返回的结果
                        result.innerHTML = xhr.response;
                    }
                }
            }


        })
    </script>

</body>

</html>
<!-- 6-取消请求.html -->


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

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

<body>
    <button>点击发送</button>
    <button>点击取消</button>
    <script>
        //获取元素对象
        const btns = document.querySelectorAll('button');
        let x = null;
        btns[0].onclick = function () {
            x = new XMLHttpRequest();
            x.open("GET", 'http://127.0.0.1:8000/delay');
            x.send();
        }

        //调用abort方法,取消请求
        btns[1].onclick = function () {
            x.abort();
        }

    </script>

</body>

</html>
<!-- 7-重复请求.html -->


<!DOCTYPE html>
<html lang="en">
<!-- 第二次点击发送的时候把第一次没有完成的请求给取消掉
让服务器始终只有一个请求在发送 -->

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重复请求问题</title>
</head>

<body>
    <button>点击发送</button>
    <script>
        //获取元素对象
        const btns = document.querySelectorAll('button');
        let x = null;

        //标识变量
        let isSending = false;//是否正在发送AJAX请求

        btns[0].onclick = function () {
            if (isSending) {//如果正在发送,则取消该请求;并创建新请求
                x.abort();
            }
            x = new XMLHttpRequest();
            //此时正在发送AJAX请求,需要修改标识变量的值
            isSending = true;
            x.open("GET", 'http://127.0.0.1:8000/delay');
            x.send();
            x.onreadystatechange = function () {
                if (x.readyState === 4) {
                    //请求完成,注意不要加状态码判断,因为很可能是失败的请求
                    isSending = false;//修改标识变量
                }
            }
        }

        //调用abort方法,取消请求
        btns[1].onclick = function () {
            x.abort();
        }

    </script>

</body>

</html>
<!-- client.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery发送AJAX请求</title>
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
</head>

<body>
    <div class="container">
        <h2 class="page-header">jQuery发送AJAX请求</h2>
        <button class="btn btn-primary">GET</button>
        <button class="btn btn-danger">POST</button>
        <button class="btn btn-info">通用型方法AJAX</button>
    </div>
    <script>
        $('button').eq(0).click(function () {
            $.get('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) {
                console.log(data);
            }, 'json');//加了json是对象
        })
        $('button').eq(1).click(function () {
            $.post('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) {
                console.log(data);
            });//不加是字符串
        })
        $('button').eq(2).click(function () {
            $.ajax({
                url: 'http://127.0.0.1:8000/jquery-server',//url
                // url:'http://127.0.0.1:8000/delay',
                data: { a: 110, b: 220 },//参数 
                type: 'GET',//请求类型
                dataType: 'json',//响应体结果
                success: function (data) {//成功的回调
                    console.log(data);
                },
                timeout: 2000,//超时的时间
                error: function () {//失败的回调,记得把url改成delay
                    console.log('出错了!!');
                },
                headers: {//头信息
                    c: 300,
                    d: 400
                }
            });
        })
    </script>

</body>

</html>
<!-- axios.html -->


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios发送AJAX请求</title>
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
</head>

<body>
    <button class="btn btn-primary">GET</button>
    <button class="btn btn-danger">POST</button>
    <button class="btn btn-info">通用型方法AJAX</button>


    <script>
        const btns = document.querySelectorAll('button');

        //配置baseURL
        axios.defaults.baseURL = 'http://127.0.0.1:8000';

        btns[0].onclick = function () {
            //GET请求,不能设置请求体,所以此处只设置了url和请求头
            axios.get('/axios-server', {
                params: {//url参数
                    id: 100,
                    vip: 7
                },
                headers: {//请求头信息
                    name: 'DDD',
                    age: 18
                }

            }).then(value => {
                console.log(value);
            });
        }

        btns[1].onclick = function () {
            axios.post('/axios-server', {
                username: 'admin',
                password: '1234'
            }, {
                //url
                params: {
                    id: 200,
                    vip: 9
                },
                //请求头参数
                headers: {
                    height: 180,
                    weight: 170
                }
                //请求体
            })
        }

        btns[2].onclick = function () {
            axios({
                //请求方法
                method: 'POST',
                //url
                url: '/axios-server',
                //url参数
                params: {
                    vip: 10,
                    level: 30
                },
                //头信息
                headers: {
                    a: 100,
                    b: 200
                },
                //请求体
                data: {
                    username: 'admin',
                    password: '1234'
                }
            }).then(response => {
                console.log(response);
                console.log(response.status);//响应状态码
                console.log(response.statusText);//响应状态字符串
                console.log(response.headers);//响应头信息
                console.log(response.data);//响应体
            })
        }
    </script>
</body>

</html>
<!-- fetch.html -->


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

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

<body>
    <button>AJAX请求</button>
    <script>
        const btn = document.querySelector('button');

        btn.onclick = function () {
            fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
                method: 'POST',//请求方法
                headers: {//请求头
                    name: 'atguigu'
                },
                body: 'username=admin&password=123'//请求体
            }).then(response => {
                // return response.text();
                return response.json();

            }).then(response => {
                console.log(response);
            })
        }
    </script>
</body>

</html>
//server.js


//1.引入express
const express = require('express');

//2.创建应用对象
const app = express();

//3.创建路由规则
//request是对请求报文的封装;response是对响应报文的封装
//以下也可以改成app.post(....),app.gett(....)

//可以接受任意类型的请求
app.all('/server', (request, response) => {
    //设置响应头,允许跨越
    response.setHeader('Access-Control-Allow-Origin', '*');
    //设置响应头,允许接收自定请求头
    response.setHeader('Access-Control-Allow-Headers', '*');
    //设置响应体
    response.send('HELLO AJAX ALL33');
});

//JSON响应
app.all('/json-server', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    //响应一个数据
    const data = {
        name: 'atguigu'
    };
    //对对象进行字符串转换(因为send只能接收字符串和buffer)
    let str = JSON.stringify(data);
    //设置响应体
    response.send(str);
});

//专门针对IE缓存
app.get('/ie', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    //设置响应体
    response.send('HELLO IE---');
});

//延时响应
app.all('/delay', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    setTimeout(() => {
        //设置响应体
        response.send('延时响应');
    }, 3000)
});

//jQuery服务
app.all('/jquery-server', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    // response.send('Hello jQuery AJAX');
    const data = { name: 'Donna' };
    response.send(JSON.stringify(data));
});

//axios服务
app.all('/axios-server', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    // response.send('Hello axios AJAX');
    const data = { name: 'Donna' };
    response.send(JSON.stringify(data));
});

//fetch服务
app.all('/fetch-server', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    // response.send('Hello fetch AJAX');
    const data = { name: 'Donna' };
    response.send(JSON.stringify(data));
});

//jsonp服务
app.all('/jsonp-server', (request, response) => {
    // response.send('Hello jsonp AJAX');//对比这两个的控制台和网络response
    //response.send('console.log("hello jsonp")');//script请求要的是函数调用的内容(js代码)返回
    const data = {
        name: 'Donna1'
    };
    //将数据转换为字符串
    let str = JSON.stringify(data);
    //返回结果
    response.end(`handle(${str})`);//end不会加特殊响应头,`是tab键上面的,而不是单引号
    //总结:返回结果的形式是函数调用,函数的参数是我们想给客户端返回的结果数据,注意函数需提前声明
});

//用户名检测是否存在
app.all('/check-username', (request, response) => {
    // response.send('Hello jsonp');//对比这两个的控制台和网络response
    //response.send('console.log("hello jsonp")');//script请求要的是函数调用的内容(js代码)返回
    const data = {
        exist: 1,
        msg: '用户名已经存在'
    };
    //将数据转换为字符串
    let str = JSON.stringify(data);
    //返回结果
    response.end(`handle(${str})`);//end不会加特殊响应头,`是tab键上面的,而不是单引号
    //总结:返回结果的形式是函数调用,函数的参数是我们想给客户端返回的结果数据,注意函数需提前声明
});

//jquery-jsonp
app.all('/jquery-jsonp-server', (request, response) => {
    // response.send('Hello jsonp');//对比这两个的控制台和网络response
    //response.send('console.log("hello jsonp")');//script请求要的是函数调用的内容(js代码)返回
    const data = {
        name: 'Donna',
        city: ['北京', '上海', '深圳']
    };
    //将数据转换为字符串
    let str = JSON.stringify(data);
    //接收callback参数
    let cb = request.query.callback;
    //返回结果
    response.end(`${cb}(${str})`);//end不会加特殊响应头,`是tab键上面的,而不是单引号
    //总结:返回结果的形式是函数调用,函数的参数是我们想给客户端返回的结果数据,注意函数需提前声明
});

//cors
app.all('/cors-server', (request, response) => {
    //设置响应头
    // response.setHeader("Access-Control-Allow-Orign","http://127.0.0.1:5500");只有5500这个端口才可以向网页发送请求
    response.setHeader("Access-Control-Allow-Origin", "*");//*表示所有端口
    response.setHeader("Access-Control-Allow-Headers", "*");
    response.setHeader("Access-Control-Allow-Methods", "*");
    response.send('hello CORS');
});

//4.监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动,8000端口监听中....");
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值