AJAX实例之发送POST请求、服务端响应JSON数据、请求超时与网络异常问题、取消请求问题、以及jQuery发送AJAX请求

一、AJAX发送POST请求:

<!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: 200px;
            border: 1px solid #903;
        }
    </style>
</head>

<body>
    <div id="result"></div>
    <script>
        // 绑定元素对象
        var result = document.getElementById('result');
        // 绑定事件
        result.addEventListener('mouseover', 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');
            xhr.setRequestHeader('name', 'zzz');
            // 3.发送
            xhr.send('a=100&b=200%c=300');

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

</html>

在server.js中写接口:

const { response } = require('express');
const express = require('express');
const app = express();

app.all('/server', (require, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    response.send('HELLO AJAX');
});

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

二、服务端响应JSON数据:

<!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: 200px;
            border: 1px solid #903;
        }
    </style>
</head>


<body>
    <div id="result"></div>
    <script>
        var 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) {
                    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.自动对数据进行转换
                        console.log(xhr.response);
                        result.innerHTML = xhr.response.name;
                    }
                }
            }
        }
    </script>
</body>

</html>

在server.js中写接口:

const { response } = require('express');
const express = require('express');
const app = express();

app.all('/json-server', (require, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Headers', '*');
    const data = {
        name: 'zzz'
    };
    let str = JSON.stringify(data);
    response.send(str);
});

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

三、请求超时与网络异常问题

<!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: 200px;
            border: 1px solid #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() {
            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');
            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>

</html>

取消请求:
如果该请求已被发出,XMLHttpRequest.abort() 方法将终止该请求。

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

        btns[1].onclick = function() {
            xhr.abort();
        }
    </script>

在server.js中写接口:

const { response } = require('express');
const express = require('express');
const app = express();

app.get('/delay', (require, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    setTimeout(() => {
        response.send('延时响应');
    }, 3000);
});

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

四、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">
    <script src="./node_modules/jquery/dist/jquery.js"></script>
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> -->
    <title>Document</title>
</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);
            }, 'json');
        })

        $('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(data) {
                    console.log('出错啦');
                },
                // 头信息
                headers: {
                    c: 300,
                    d: 400
                },
            })
        })
    </script>
</body>

</html>

在server.js中写接口:

const { response } = require('express');
const express = require('express');
const app = express();

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

app.listen(8000, () => {
    console.log('服务器已启动');
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值