AJAX学习记录

58 阅读3分钟

AJAX学习记录

HTTP协议

超文本传输协议(Hypertext[ Transfer Protocol](baike.baidu.com/item/ Transfer Protocol/612755?fromModule=lemma_inlink),HTTP)是一个简单的请求-响应协议,它通常运行在TCP之上。它指定了客户端可能发送给服务器什么样的消息以及得到什么样的响应。请求和响应消息的头以ASCII形式给出;而消息内容则具有一个类似MIME的格式。超文本传输协议是一种用于分布式、协作式和超媒体信息系统的应用层协议,是万维网WWW(World Wide Web)的数据通信的基础。

请求报文

重点是格式与参数

  • 行 POST /s?ie = utf-8 http/1.1

  • 头 Host:atguigu.com

    ​ Cookie:name

    ​ Content-type:application/x-www-form-urlencoded

    ​ User-Agent : chrome 83

  • 空行

  • 体 username = admin&password = admin

响应报文

  • 行 HTTP/1.1 200 ok

  • 头 Content_Type:text/html;charset = utf-8

    ​ Content-length :2048

    ​ Content-encoding:gzip

  • 空行

  • EXPRESS

    引入express模块

    const expresss = require ('express');
    

    创建express 实例

    const app = express();
    

    创建路由规则

    app.get('/',(req,res)=>{
    	//设置响应头
    	res.setHeader('Access-Contorl-Allow-Origin','*')
    	//设置响应体
    	res.send('hello   AJAX' )
    })
    

    设置监听

    app.listen(8000,()=>{
    	cosole.log('服务器启动成功')
    })
    

    发出请求的网页

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .result {
                width: 200px;
                height: 100px;
                border: solid 1px black;
            }
        </style>
    </head>
    
    <body>
        <div class="result"></div>
        <script>
            const result = document.querySelector(".result");
    
            result.addEventListener('mouseover', () => {
                console.log(111);
                //创建xhr对象
                const xhr = new XMLHttpRequest();
                //设置请求方式和类型
                xhr.open("POST", "http://127.0.0.1:8000/server")
                //发送请求
                xhr.send();
    
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            console.log(xhr.status);//状态吗
                            console.log(xhr.statusText)//状态字符串
                            console.log(xhr.getAllResponseHeaders());//响应头
                            console.log(xhr.response);//响应体
                            result.innerHTML = xhr.response;
                        }
                    }
    
                }
            })
    
        </script>
    </body>
    
    </html>
    

    /创建xhr对象

    const xhr = new XMLHttpRequest();
    

//设置请求方式和类型

xhr.open("POST", "http://127.0.0.1:8000/server")

//设置请求头信息

 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
 xhr.setRequestHeader('name','linjiangtao')

//发送请求

 xhr.send();

//4.获取响应

 xhr.onreadystatechange = function () {
            if(xhr.readyState === 4){
                if(xhr.status >=200&&xhr.status < 300|| xhr.status === 304 ){
                    // 处理结果  行 头 空行 体
                    //1.获取响应行
                    console.log(xhr.status);//状态吗
                    console.log(xhr.statusText)//状态字符串
                    console.log(xhr.getAllResponseHeaders());//响应头
                    console.log(xhr.response);//响应体
                    result.innerHTML = xhr.response;
                }else{
                    
                }
            }
        }

解决IE缓存问题

xhr.open('GET', 'http://127.0.0.1:8000/4IE?t='+Date.now());

因为IE浏览器有缓存机制,回导致相同名字的请求的结果相同;所以加上时间戳

请求超时与网络异常

请求超时

 //超时操作
            xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function () {
                alert('请求超时');
            }

网络异常

//网络异常
            xhr.onerror = function () {
                alert('网络异常');
            }

EXPRESS超时模拟

const express = require('express');
const app  = express();
app.all('/time',(req,res)=>{

    //设置响应头
    res.setHeader('Access-Control-Allow-Origin','*')
    //设置响应体
    setTimeout(()=>{
        res.send('延长请求时间')
    },3000)
    //  res.send('HELLO IE缓存问题');
    

});
app.listen(8000,()=>{
    console.log('服务器启动成功');
});

用户重复点击问题

解决方法:创建一个标识头

 <script>
        const btnF = document.querySelector('#btn1');
        const btnS = document.querySelector('#btn2');
        let xhr = null
        let isSending = false; // 判断是否正在发送请求
        btnF.onclick = function () {
            
            if (isSending) {
                xhr.abort(); // 如果正在发送请求,则取消请求,创建新的请求
            }
             xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open('get', 'http://127.0.0.1:8000/time');
            xhr.send();
            // xhr.onreadystatechange = function () {

            // }
            // abort 取消请求
            btnS.onclick = function () {
                xhr.abort();
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    isSending = false;
                }
            }
        }
    </script>

AXIOS(****)

配置 baseURL

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

GET方法发送请求

const btn = document.querySelectorAll('button');
        btn[0].onclick = function () {
            //GET
            axios.get('/xiosServer', {
                //url参数(小写)
                params: {
                    id: 100,
                    vip: 7
                },
                //请求头信息(小写)
                headers: {
                    name: 'linjuntao',
                    age: '18'
                }
            }).then(value => {
                console.log(value);
            })

        }

POST方法发送请求

 btn[1].onclick = function () {
            //GET
            axios.post('/xiosServer', {
                username: 'admin',
                password: 'asmin'
            }, {
                //url参数(小写)
                params: {
                    id: 100,
                    vip: 7
                },
                //请求头信息(小写)
                headers: {
                    name: 'linjuntao',
                    age: '18'
                }
            }).then(value => {
                console.log(value);
            })

        }

AJAX函数方法发送请求(***)

 btn[2].onclick = function () {
            axios({
                //请求方式
                method: 'POST',
                //请求地址
                url: '/xiosServer',
                //请求参数
                params: {
                    vip: 10,
                    level: 100
                },
                //请求头信息
                headers: {
                    a: 100,
                    b: 200
                }
            }).then(response =>{
                //响应状态码.
                console.log(response.status);
                //响应字符串
                console.log(response.statusText);
                //响应头信息
                console.log(response.headers);
                //响应体
                console.log(response.data);
            })

FETCH方法发送请求

 const btn = document.querySelector('button');
        btn.addEventListener('click', () => {
            fetch('http://127.0.0.1:8000/fetch-server'),{
                //请求方法
                method:'POST',
                headers:{
                    name:'lin',
                },
                body:'username=admin&password=admin'
            }
        }).then(response=>{
            return response.json();
        }).then(response =>{
            console.log(response);
        } )

同源策略

同源:域名,协议,端口必须一致

解决跨域问题

<script src="http://127.0.0.1:8000/JSONP-server"></script>

2

cors