AJAX请求

一、Ajax基础使用

1.创建一个get请求

        //1.创建对象
        const xhr = new XMLHttpRequest();
        
        //2.初始化 设置请求方法和URL
        xhr.open('GET','http://127.0.0.1:8080/server');
       
        //3.发送
        xhr.send();
        
        //4.事件绑定 处理服务端返回结果
        //on 当...时候
        //readystate 是 xhr对象中的属性,表示状态0 1 2 3 4
        //change 改变
        xhr.onreadystatechange=function(){
            if(xhr.readyState ===4){
                //判断服务端返回了所有结果
                if(xhr.status >= 200 && xhr.status < 300){
                    //判断响应状态码 200 404 403 401 500
                    //2xx 成功
                    div.innerHTML=xhr.response.name
                }
            }
        }

请求超时
xhr.timeout = 2000 ; 2秒后取消请求
超时回调
xhr.ontimeout = function(){}
请求错误
xhr.onerror = function(){}
取消请求
xhr.abrot()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>get请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid rebeccapurple;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        var btu = document.getElementsByTagName('button')[0]
        var div = document.getElementById('result')
        btu.onclick=function(){
            //1.创建对象
            const xhr = new XMLHttpRequest();

            //设置响应体数据类为json,不是则不设置,否则报错
            xhr.responseType = 'json'
            
            //2.初始化 设置请求方法和URL
            xhr.open('GET','http://127.0.0.1:8080/server');
            
            //设置请求头
            //参数1:头名字
            //参数2:值
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            //3.发送
            xhr.send();
            //4.事件绑定 处理服务端返回结果
            //on 当...时候
            //readystate 是 xhr对象中的属性,表示状态0 1 2 3 4
            //change 改变
            xhr.onreadystatechange=function(){
                if(xhr.readyState ===4){
                    //判断服务端返回了所有结果
                    if(xhr.status >= 200 && xhr.status < 300){
                        //判断响应状态码 200 404 403 401 500
                        //2xx 成功
                        div.innerHTML=xhr.response.name
                        console.log(xhr.status)//状态吗
                        console.log(xhr.statusText)//状态字符串
                        console.log(xhr.getAllResponseHeaders)//所有响应头
                        console.log(xhr.response)//响应体
                    }
                }
            }
        }
    </script>
</body>
</html>

2.npm init --yes
3.npm i express (安装express模拟服务器)
4.npm i -g nodemon (安装nodemon改服务器代码时不需要重启)
5.模拟一个服务器server.js
node server.js(运行)
nodemon server.js(运行)

//1.引入
const { json } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/server',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*')
    const data ={
        name:'lihua'
    }
    let str =JSON.stringify(data)
     response.send(str);
})
//all什么请求都能接收
app.all('/server',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*')
    const data ={
        name:'lihua'
    }
    let str =JSON.stringify(data)
     response.send(str);
})
//4.监听启动服务
app.listen(8080,()=>{
    console.log("服务已经启动,8080端口监听中");
});

在这里插入图片描述

二、解决IE缓存问题

在连接后传一时间戳

xhr.open('GET','http://127.0.0.1:8080/server?t='+Date.now());

三、解决重复请求问题

定义一个布尔值变量isSending来使用abort()取消上一次请求
被取消的请求状态为(canceled)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>get请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid rebeccapurple;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        var btu = document.getElementsByTagName('button')[0]
        var div = document.getElementById('result')
        let isSending = false
        let xhr = null
        btu.onclick=function(){
            if(isSending) xhr.abort()
            xhr = new XMLHttpRequest();
            isSending = true
            xhr.open('GET','http://127.0.0.1:8080/server?t='+Date.now());
            xhr.send();
            xhr.onreadystatechange=function(){
                if(xhr.readyState ===4){
                    //判断服务端返回了所有结果
                    isSending = false
                    div.innerHTML=xhr.response
                }
            }
        }
    </script>
</body>
</html>

四、jQuery发送Ajax请求

$.get()
第一个参数:URL:‘http://127.0.0.1:8080/jquery’
第二个参数:数据:{a:10,b:20}
第三个参数:回调函数:function(data){}
第四个参数:响应体:‘json’

 $.get('http://127.0.0.1:8080/jquery',{a:10,b:20},function(data){
            console.log(data)
            $('#result').text(data.name)
        },'json')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jqget请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid rebeccapurple;
        }
    </style>
</head>
<body>
    <button>发送get请求</button>
    <button>发送post请求</button>
    <div id="result"></div>
    <script type="text/javascript" src="../jquery.js"></script>
    <script>
    $('button').eq(0).click(function(){
        $.get('http://127.0.0.1:8080/jquery',{a:10,b:20},function(data){
            console.log(data)
            $('#result').text(data.name)

        },'json')
    })
    $('button').eq(1).click(function(){
        $.post('http://127.0.0.1:8080/jquery',function(data){
            console.log(data)
            $('#result').text(data.name)

        },'json')
    })
    </script>
</body>
</html>

服务器

app.all('/jquery',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*')
    const data ={
        name:'lihua'
    }
    let str =JSON.stringify(data)
     response.send(str);
})

五、jQuery通用方法发送Ajax请求

 $.ajax({
            url:'http://127.0.0.1:8080/jquery',
            data:{a:10,b:20},
            type:'GET',
            dataType:'json',
            success:function(res){
                console.log(res)
                $('#result').text(res.name)
            },
            timeout:2000,
            error(){
                alert("请求超时")
            },
            //自定义请求头
            headers:{
                c:300,
                d:400
            }
        }) 
    $('button').eq(2).click(function(){
        $.ajax({
            url:'http://127.0.0.1:8080/jquery',
            data:{a:10,b:20},
            type:'GET',
            dataType:'json',
            success:function(res){
                console.log(res)
                $('#result').text(res.name)
            },
            timeout:2000,
            error(){
                alert("请求超时")
            },
            //自定义请求头
            headers:{
                c:300,
                d:400
            }
        })   
    })

服务器

app.all('/jquery',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*')
    //前端自定义请求头处理
    response.setHeader('Access-Control-Allow-Headers','*')
    const data ={
        name:'lihua'
    }
    let str =JSON.stringify(data)
     response.send(str);
})

六、Axios发送ajxs请求

bata为请求体,config其他配置
1.get请求axios.get(url,{config})

axios.get('http://127.0.0.1:8080/axios',{
                //参数
                params:{
                    id:1,
                    vip:1
                },
            }).then(res=>{
                console.log(res)
                div.innerHTML=res
            })

2.post请求axios.post(url,{data},{config})

axios.post('http://127.0.0.1:8080/axios',{
                //请求体
                data:{
                    name:'admin',
                    password:'admin'
                }
            },{
                //参数
                params:{
                    id:2,
                    vip:2
                },
                //自定义请求头
                headers:{
                    height:180,
                    weight:180
                }
            }).then(res=>{
                console.log(res)
                div.innerHTML=res
            })   
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原生ajaxget请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid rebeccapurple;
        }
    </style>
</head>
<body>
    <button>点击发送get请求</button>
    <button>点击发送post请求</button>
    <div id="result"></div>
    <script>
        var btu = document.getElementsByTagName('button')[0]
        var btu1 = document.getElementsByTagName('button')[1]
        var div = document.getElementById('result')
        btu.onclick=function(){
            axios.get('http://127.0.0.1:8080/axios',{
                //参数
                params:{
                    id:1,
                    vip:1
                },
                //自定义请求头
                headers:{
                    name:"lihua",
                    age:20
                },
                dataType:'json'
            }).then(res=>{
                console.log(res)
                div.innerHTML=res.data.name
            })
        },    
            btu1.onclick=function(){
            axios.post('http://127.0.0.1:8080/axios',{
                //请求体
                data:{
                    name:'admin',
                    password:'admin'
                }
            },{
                //参数
                params:{
                    id:2,
                    vip:2
                },
                //自定义请求头
                headers:{
                    height:180,
                    weight:180
                }
            }).then(res=>{
                console.log(res)
                div.innerHTML=res
            })   
        }
    </script>
</body>
</html>

七、Axios函数发送ajxs请求

1.GET请求

axios({
                url:'http://127.0.0.1:8080/axios',
                params:{
                    vip:1
                },
                method:'GET',
            }).then(res=>{
                console.log(res)
                div.innerHTML=res.data.name
            }) 

2.POST请求

axios({
                url:'http://127.0.0.1:8080/axios',
                data:  //请求体
                params:{       //参数
                    vip:1
                },
                method:'POST',
            }).then(res=>{
                console.log(res)
                div.innerHTML=res.data.name
            }) 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原生ajaxget请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid rebeccapurple;
        }
    </style>
</head>
<body>
    <button>点击发送post请求</button>
    <div id="result"></div>
    <script>
        var btu = document.getElementsByTagName('button')[0]
        var div = document.getElementById('result')
        btu.onclick=function(){
            axios({
                url:'http://127.0.0.1:8080/axios',
                params:{
                    vip:1
                },
                method:'POST',
                dataType:'json'
            }).then(res=>{
                console.log(res)
                div.innerHTML=res.data.name
            }) 
        } 
    </script>
</body>
</html>

服务器

app.all('/axios',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-Control-Allow-Origin','*')
    //前端自定义请求头处理
    response.setHeader('Access-Control-Allow-Headers','*')
    const data ={
        name:'lihua'
    }
    let str =JSON.stringify(data)
     response.send(str);
})

八、fetch发送ajax请求

在这里插入图片描述

九、解决跨域问题

首先是proxy

其次是cors

jsonp最后

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值