AJAX基础

一.server

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

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

//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    //设置响应头 设置允许自填
    response.setHeader('Access-Control-Allow-Headers','*');
    //设置响应体
    response.send('HELLO AJAX GET');
});

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

app.all('/json-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    //设置响应头 设置允许自填
    response.setHeader('Access-Control-Allow-Headers','*');
    //响应一个数据
    const data = {
        name: 'WuM1ng'
    };
    //对对象进行字符串转换
    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('HELLO Delay');
    },1000)
});

//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: 'WuM1ng'};
    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 jQuery AJAX');
    const data = {name: 'WuM1ng'};
    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 jQuery AJAX');
    const data = {name: 'WuM1ng'};
    response.send(JSON.stringify(data));
});

//jsonp 服务
app.all('/jsonp-server',(request, response) =>{
    // response.send('console.log("hello jsonp-server")');
    const data = {
        name: 'WuM1ng'
    };
    //将数据转化为字符串
    let str = JSON.stringify(data);
    //返回结果
    response.end(`handle(${str})`);
})

//用户名检测是否存在
app.all('/check-username',(request, response) =>{
    // response.send('console.log("hello jsonp-server")');
    const data = {
        exist: 1,
        msg: '用户名已经存在'
    };
    //将数据转化为字符串
    let str = JSON.stringify(data);
    //返回结果
    response.end(`handle(${str})`);
})

//
app.all('/jquery-jsonp-server',(request, response) =>{
    // response.send('console.log("hello jsonp-server")');
    const data = {
        name:'WuM1ng',
        city:['beijing','shanghai','shenzhen']
    };
    //将数据转化为字符串
    let str = JSON.stringify(data);
    //接收 callback 参数
    let cb = request.query.callback;

    //返回结果
    response.end(`${cb}(${str})`);
});

app.all('/cors-server',(request, response)=>{
    //设置响应头
    response.setHeader("Access-Control-Allow-Origin","*");
    response.setHeader("Access-Control-Allow-Headers","*");
    response.setHeader("Access-Control-Allow-Method","*");
    response.send('hello CORS');
})

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

二.原生AJAX

1-GET

<!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. 初始化
            xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');
            //3. 发送
            xhr.send();
            //4. 事件绑定 处理服务端返回结果
            xhr.onreadystatechange = function(){
                //判断
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // //处理结果
                    // //响应
                    // console.log(xhr.status);//状态码
                    // console.log(xhr.statusText);//状态字符串
                    // console.log(xhr.getAllResponseHeaders());//所有响应头
                    // console.log(xhr.response);//响应体

                    //设置result的文本
                    result.innerHTML = xhr.response;
                }
            }
        }
    </script>
</body>
</html>

2-POST

<!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>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        //获取元素对象
        const result = document.getElementById("result");
        //绑定事件
        result.addEventListener("mouseover",function(){
            //1. 创建对象
            const xhr = new XMLHttpRequest();
            //2. 初始化设置
            xhr.open('POST','http://127.0.0.1:8000/server');
            //设置请求头
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.setRequestHeader('name','WuM1ng');
            //3. 发送
            xhr.send('a=100&b=200&c=300');
            //4. 事件绑定
            xhr.onreadystatechange = function(){
                //判断
                if (xhr.readyState === 4 && xhr.status === 200){
                    //处理服务端返回结果
                    result.innerHTML = xhr.response;
                }
            }
        })
    </script>
</body>
</html>

3-JSON

<!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 #89b;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        const result = document.getElementById('result');
        //绑定键盘按下事件
        window.onkeydown = function(){
            //发送请求
            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 && xhr.status === 200){
                    //处理服务端返回结果
                    // console.log(xhr.response);
                    // result.innerHTML = xhr.response;
                    //手动对数据进行转化
                    // let data = JSON.parse(xhr.response);
                    // console.log(data);
                    // result.innerHTML = data.name;
                    //自动对数据转化
                    console.log(xhr.response);
                    result.innerHTML = xhr.response.name;
                }
            }
        }
    </script>
</body>
</html>

4-IE CACHING

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IE CACHING</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #258;
        }
    </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(){
            const xhr = new XMLHttpRequest();
            xhr.open('GET','http://127.0.0.1:8000/ie?t='+Date.now());
            xhr.send();
            xhr.onreadystatechange = function(){
                if (xhr.readyState === 4 && xhr.status === 200){
                    result.innerHTML = xhr.response;
                }
            }
        })
    </script>
</body>
</html>

5-超时与网络异常

<!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 #90b;
        }
    </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(){
            const xhr = new XMLHttpRequest();
            //超时设置
            xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function(){
                alert("网络异常请稍后重试!");
            }
            //网络异常回调
            xhr.onerror = function(){
                alert("网络出现问题!");
            }
            xhr.open('GET','http://127.0.0.1:8000/delay');
            xhr.send();
            xhr.onreadystatechange = function(){
                if (xhr.readyState === 4 && xhr.status === 200){
                    result.innerHTML = xhr.response;
                }
            }
        })
    </script>
</body>
</html>

6-取消请求

<!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-重复请求问题

<!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();
            //修改表示变量的值
            isSending = true;
            x.open('GET','http://127.0.0.1:8000/delay');
            x.send();
            x.onreadystatechange = function(){
                if(x.readyState === 4){
                    //修改标识变量
                    isSending = false;
                }
            }
        }
    </script>
</body>
</html>

三.jQuery-AJAX

<!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>
    <link crossorigin="anonymous" href="">
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.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');
        })
        $('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
                url: 'http://127.0.0.1:8000/jquery-server',
                //参数
                data: {a:100,b:200},
                //请求类型
                type: 'GET',
                //响应体结果
                dataType: 'json',
                //成功的回调
                success: function(data){
                    console.log(data);
                },
                //超时时间
                timeout: 2000,
                //失败的回调
                error: function(){
                    console.log('出错了!');
                },
                //头信息设置
                headers: {
                    c:300,
                    d:400
                },
            })
        })
    </script>
</body>
</html>

四.axios-AJAX

<!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>GET</button>
    <button>POST</button>
    <button>AJAX</button>
    <script>
        const btns = document.querySelectorAll('button');
        //配置 baseURL
        axios.defaults.baseURL = 'http://127.0.0.1:8000';
        btns[0].onclick = function(){
            //GET 请求
            axios.get('/axios-server',{
                //url 参数
                params: {
                    id:100,
                    vip:7
                },
                // 请求头信息
                headers: {
                    name:'WuM1ng',
                    age:19
                }
            }).then(value =>{
                console.log(value);
            });       
        }
        btns[1].onclick = function(){
            axios.post('/axios-server', 
                    //请求体
                    {
                    username:'admin',
                    password:'admin'
                },{
                //url
                params: {
                    id: 200,
                    vip: 9
                },
                //请求头参数
                headers: {
                    height:180,
                    weight:180,
                }
            });
        }
        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: 'admin',
                }
            }).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-AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>fetch 发送 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:'WuM1ng'
                },
                //请求体
                body: 'username=admin&password=admin'
            }).then(response => {
                // return response.text();
                return response.json();
            }).then(response =>  {
                console.log(response);
            });
        }
    </script>
</body>
</html>

六.跨域

1-同源策略

<!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>
    <h1>WuM1ng</h1>
    <button>点击获取用户数据</button>
    <script>
        const btn = document.querySelector('button');
        btn.onclick = function(){
            const x = new XMLHttpRequest();
            //满足同源策略,url可以简写
            x.open("GET",'/data');
            //发送
            x.send();
            //判断
            x.onreadystatechange = function(){
                if (x.readyState === 4 && x.status === 200){
                    console.log(x.response);
                }
            }
        }
    </script>
</body>
</html>
const express = require('express');
const app = express();
app.get('/home',(request,response)=>{
    //响应一个页面
    response.sendFile(__dirname + '/index.html');
});

app.get('/data',(request,response)=>{
    response.send('用户数据');
});

app.listen(9000, ()=>{
    console.log("服务已经启动")
})

2-JSONP

const data = {
    name: 'WuM1ng'
};

handle(data);

1.原理

<!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: 300px;
            height: 100px;
            border: solid 1px #78a;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
    //处理数据
    function handle(data){
        //获取result元素
        const result = document.getElementById('result');
        result.innerHTML = data.name;
    }
    </script>
    <!-- <script src="http://127.0.0.1:5500/code/05.%E8%B7%A8%E5%9F%9F/2-JSONP/js/app.js"></script> -->
    <script src="http://127.0.0.1:8000/jsonp-server"></script>
</body>
</html>

2.JSONP实践

<!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>
    用户名: <input type="text" id="username">
    <p></p>
    <script>
        //获取input元素
        const input = document.querySelector('input');
        const p = document.querySelector('p');
        //声明 handle 函数
        function handle(data){
            input.style.border = "soild 1px #f00";
            //修改 p 标签提示文本
            p.innerHTML = data.msg;
        }
        //绑定事件
        input.onblur = function(){
            //获取用户输入值
            let username = this.value;
            //向服务端发送请求 检测用户名是否存在
            //1. 创建 script 标签
            const script = document.createElement('script');
            //2. 设置标签 src 属性
            script.src = 'http://127.0.0.1:8000/check-username';
            //3. 将 script 插入到文档中
            document.body.appendChild(script);
        }
    </script>
</body>
</html>

3.jQuery-jsonp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery-jsonp</title>
    <style>
        #result{
            width: 300px;
            height: 100px;
            border: solid 1px #089;
        }
    </style>
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
</head>
<body>
    <button>点击发送 jsonp 请求</button>
    <div id="result"></div>
    <script>
        $('button').eq(0).click(function(){
            $.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?',function(data){
                $('#result').html(`
                    名称: ${data.name},
                    校区: ${data.city}
                `)
            });
        });
    </script>
</body>
</html>

3-CORS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>发送请求</button>
    <div id="result"></div>
    <script>
        const btn = document.querySelector('button');
        btn.onclick = function(){
            //1.创建对象
            const x = new XMLHttpRequest();
            //2.初始化设置
            x.open("GET","http://127.0.0.1:8000/cors-server");
            //3.发送
            x.send();
            //4.绑定事件
            x.onreadystatechange = function(){
                if (x.readyState === 4 && x.status === 200){
                    console.log(x.response);
                }
            }
        }
    </script>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值