Ajax系列---【Ajax原生、jQuery发送Ajax、Axios发送Ajax、Fetch发送Ajax、解决跨域操作步骤】

原生方法发送Ajax请求---原生Ajax
1.Ajax简介

全称为Asynchronous JavaScript And XML,就是异步的JS和XML,通过AJAX可以在浏览器中向服务器发送异步请求,最大的优势是:无刷新获取数据

2.XML简介:

是可扩展标记语言,是用来传输和存储数据

3.Ajax的优点和缺点

1)优点:

可以无需刷新页面与服务器进行通信。

允许你根据用户事件来个更新部分页面内容。

2)缺点:

没有浏览历史,不能回退。

存在跨域问题。

SEO不友好。(用AJAX无刷新读出来的东西,查看原代码的时候不会出现在里面。爬虫捕捉不到关键字,那样就会印象SEO优化效果)

4.http协议请求报文和响应报文结构

1)请求报文

一个HTTP请求报文由请求行(request line)、请求头部(header)、空行和请求数据(请求体)4个部分组成,下图给出了请求报文的一般格式。

请求行:由请求方法字段、URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔。例如,GET /index.html HTTP/1.1。(HTTP协议的请求方法有GET、POST、HEAD、PUT、DELETE、OPTIONS、TRACE、CONNECT。)

请求头部:由关键字/值对组成,每行一对,关键字和值用英文冒号“:”分隔。请求头部通知服务器有关于客户端请求的信息,典型的请求头有:

User-Agent:产生请求的浏览器类型。

Accept:客户端可识别的内容类型列表。

Host:请求的主机名,允许多个域名同处一个IP地址,即虚拟主机。

空行:最后一个请求头之后是一个空行,发送回车符和换行符,通知服务器以下不再有请求头。

请求数据(请求体):不在GET方法中使用,而是在POST方法中使用

2)响应报文

响应报文同上有三个结构构成,只不过请求行是显示状态行:HTTP-Version Status-Code Reason-Phrase CRLF(HTTP-Version表示服务器HTTP协议的版本;Status-Code表示服务器发回的响应状态代码;Reason-Phrase表示状态代码的文本描述。例:HTTP/1.1 200 OK)

5.Ajax的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid #ccc;
        }
​
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <button>点击取消请求</button>
    <div id="result"></div>
</body>
<script>
    // 获取元素
    const btns = document.querySelectorAll('button');
    const result = document.getElementById('result');
    // 1.创建对象
    let xhr = null
    // 标识变量
    let isSending = false; // 是否正在发送ajax请求
    // 绑定事件--发送请求
    btns[0].onclick = function(){
        // 判断标识变量
        if(isSending) xhr.abort() // 如果正在发送,则取消发送。创建一个新的请求
        // 1.创建对象(0状态)
        xhr = new XMLHttpRequest();
        // 修改标识
        isSending = true
        // 超时设置2s
        // xhr.timeout = 2000
        // 超时回调
        // xhr.ontimeout = function(){
        //     alert('网络超时,请重试')
        // }
        // 网络异常回调
        // xhr.onerror = function(){
        //     alert('网络出现问题啦!')
        // }
        // 直接设置响应体数据的类型()
        xhr.responseType = 'json'
        // 2.初始化。设置请求头、请求方式、url(1状态)
        // GET请求url拼接参数
        // xhr.open('GET','http://127.0.0.1:8000/serve?a=100&b=200&c=300');
        // POST请求参数写在send中
        // xhr.open('POST','http://127.0.0.1:8000/serve');
        // ie浏览器针对发送请求存在缓存问题,解决方法是加时间戳
        xhr.open('POST','http://127.0.0.1:8000/serve?='+ Date.now());
        
        // 设置请求头
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlenxoded')
​
        // 3.发送(2状态)
        // xhr.send()
        xhr.send('a=100&b=200&c=300')
        // 4.事件绑定,处理服务器返回来的结果
        // readystate是xhr对象中的属性,表示状态0,1,2,3,4
        // change 改变
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                // 判断相应状态码 200 404 403 ...;2xx表示成功
                if(xhr.status >= 200 && xhr.status < 300 ){
                    // 处理结果 行 头 空行 体
                    console.log(xhr.status); // 状态码
                    console.log(xhr.statusText); // 状态字符串
                    console.log(xhr.getAllResponseHeaders); // 所有响应头
                    console.log(xhr.response); // 响应体
                    // 设置响应体数据的类型的方法(如果后端返回的不是json格式的数据,需转换)
                    // 1) 手动对数据转换
                    let data = JSON.parse(xhr.response)
                    // 2)直接设置响应体数据的类型(如例:第29行)
​
​
                    // 设置result的文本
                    // 返回的数据是json格式的直接展示
                    // result.innerHTML = xhr.response;
                    // 数据转化之后回显
                    // result.innerHTML = data;
                }else{
                    
                }
            }
        }   
    }
    btns[1].onclick = function(){
        xhr.abort()
    }
​
</script>
</html>
6.post和get请求参数的设置
// GET请求url拼接参数
xhr.open('GET','http://127.0.0.1:8000/serve?a=100&b=200&c=300');
// POST请求参数写在send中
xhr.open('POST','http://127.0.0.1:8000/serve');
7.发送post/get请求
btns[0].onclick = function(){ 
        // 1.创建对象(0状态
        xhr = new XMLHttpRequest();
        
        // 2.初始化。设置请求头、请求方式、url(1状态)
        // GET请求url拼接参数
        // xhr.open('GET','http://127.0.0.1:8000/serve?a=100&b=200&c=300');
        // POST请求参数写在send中
        // xhr.open('POST','http://127.0.0.1:8000/serve');
      
        // 3.发送(2状态)
        // xhr.send() // get请求括号不跟参数
        xhr.send('a=100&b=200&c=300')
        
        // 4.事件绑定,处理服务器返回来的结果
        // readystate是xhr对象中的属性,表示状态0,1,2,3,4
        // change 改变
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                // 判断相应状态码 200 404 403 ...;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.innerHTML = xhr.response;
                }else{
                    
                }
            }
        }   
    }
8.post请求设置请求头信息
 // 设置请求头
 xhr.setRequestHeader('Content-Type','application/x-www-form-urlenxoded')
9.处理响应数据
 // 设置响应体数据的类型的方法(如果后端返回的不是json格式的数据,需转换)
 // 1) 手动对数据转换
 let data = JSON.parse(xhr.response)
 // 2)直接设置响应体数据的类型
 xhr.responseType = 'json'
10.解决Ajax在IE浏览器缓存问题
// ie浏览器针对发送请求存在缓存问题,解决方法是加时间戳做标识,告诉浏览器这是不同的请求
xhr.open('POST','http://127.0.0.1:8000/serve?='+ Date.now());
11.Ajax解决请求超时和网络异常处理
// 超时设置2s
xhr.timeout = 2000
// 超时回调
xhr.ontimeout = function(){
    alert('网络超时,请重试')
}
// 网络异常回调
xhr.onerror = function(){
     alert('网络出现问题啦!')
}
12.Ajax取消请求
 // 点击取消按钮取消请求
 btns[1].onclick = function(){
     xhr.abort()
 }
13.Ajax请求重复发送问题
 // 全局声名标识变量
 let isSending = false; // 是否正在发送ajax请求
 
// 判断标识变量
if(isSending) xhr.abort() // 如果正在发送,则取消发送。创建一个新的请求
// 1.创建对象(0状态)
xhr = new XMLHttpRequest();
// 修改标识
isSending = true
Jquery发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 1.引入jquery库 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="box">
        <button>发送get请求</button>
        <button>发送post请求</button>
        <button>发送jsonp请求</button>
        <button>通用型方法发送ajax请求</button>
        <div id="box"></div>
    </div>
    
</body>
<script>
    // GET请求
    $('button').eq(0).click(function(){
        $.get('http://127.0.0.1:8000/xxxx',{a:100,b:200},function(data){
            console.log(data);
        })
    })
​
    // POST请求
    $('button').eq(1).click(function(){
        $.get('http://127.0.0.1:8000/xxxx',{a:100,b:200},function(data){
            console.log(data);
        })
    })
    // jq发送jsonp请求
    $('button').eq(2).click(function(){
        $.getJSON('http://127.0.0.1:8000/xxxx',{a:100,b:200},function(data){
            console.log(data);
            $('#box').html(`
                名称:${data.name},
                校区:${data.city}
            `)
        })
    })
​
    // 通用型发送Ajax请求
    $('button').eq(3).click(function(){
        $.ajax({
            // ull
            url:'http://127.0.0.1:8000/xxxx',
            // 设置参数
            data:{a:100,b:200},
            // 设置请求类型
            type: 'GET',
            // 设置响应体结果类型
            dataType:'json',
            // 成功时的回调
            success:function(data){
                console.log(data);
            },
            // 超时事件
            timeout:2000,
            // 失败的回调
            error:function(){
                console.log('出错了');
            },
            // 头信息
            headers:{
                a:200,
                b:100
            }
        })
    })
</script>
</html>
Axios发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 1.引入jquery库 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="box">
        <button>发送get请求</button>
        <button>发送post请求</button>
        <button>通用型方法发送ajax请求</button>
    </div>
    
</body>
<script>
    const btns = document.querySelectorAll('button');
​
    // 配置 baseURL
    axios.defaults.baseURL = 'http://127.0.0.1:8000'
    // GET请求
    btns[0].onclick = function(){
        axios.get('/xxxxx',{
            // url参数
            params:{
                id:100,
                vip:1
            },
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            }
        }).then(value=>{
            console.log(value);
        })
    }
​
    // POST请求
    btns[1].onclick = function(){
        axios.post('/xxxxx',{
            userName:'zhangsna',
            age:19
        },{
            // url参数
            params:{
                id:100,
                vip:1
            },
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            }
        }).then(value=>{
            console.log(value);
        })
    }
    
    // 通用型发送Ajax请求
    btns[2].onclick = function(){
        axios({
            // 请求方法
            method:'POST',
            // URL
            url:'/xxxx',
             // url参数
             params:{
                id:100,
                vip:1
            },
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            },
            // 请求体参数
            data:{
                userName:'zhangsna',
                age:19
            }
        }).then(response=>{
            console.log(res.status);
            console.log(res.statusText);
            console.log(res.headers);
            console.log(res.data);
        })
    }
</script>
</html>
Fetch发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="box">
        <button>fetch发送ajax请求</button>
    </div>
    
</body>
<script>
    const btns = document.querySelector('button');
​
    // 配置 baseURL
    axios.defaults.baseURL = 'http://127.0.0.1:8000'
    // 请求
    btn.onclick = function(){
        fetch('/xxxxx',{
            // 请求方式
            method:'POST',
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            },
            // 请求体
            body:'username=admin&pass=admin',
           
        }).then(response=>{
            return response.text();
        }).then(response=>{
            console.log(response);
        })
    }
​
    // POST请求
    btns[1].onclick = function(){
        axios.post('/xxxxx',{
            userName:'zhangsna',
            age:19
        },{
            // url参数
            params:{
                id:100,
                vip:1
            },
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            }
        }).then(value=>{
            console.log(value);
        })
    }
    
    // 通用型发送Ajax请求
    btns[2].onclick = function(){
        axios({
            // 请求方法
            method:'POST',
            // URL
            url:'/xxxx',
             // url参数
             params:{
                id:100,
                vip:1
            },
            // 请求头信息
            headers:{
                name:'zhangsan',
                age:200
            },
            // 请求体参数
            data:{
                userName:'zhangsna',
                age:19
            }
        }).then(response=>{
            console.log(res.status);
            console.log(res.statusText);
            console.log(res.headers);
            console.log(res.data);
        })
    }
</script>
</html>
解决跨域问题

 ....未完待更新中

 

 

posted on 2022-04-02 14:13  码农小小海  阅读(69)  评论(0编辑  收藏  举报

导航