六、AJAX编程

一、基本介绍

  • AJAX(Asynchronous JavaScript And XML): 异步的js和xml
  • 在浏览器中向服务器发送异步请求,实现无刷新获取数据
  • 不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式

1. 应用

  • 网站的搜索功能的提示词
  • 页面注册时候的用户名去重验证
  • 页面的按需加载,懒加载

2. 优缺点

# 优点
1. 无需刷新页面,就可以与服务器进行交互
2. 根据用户选择事件,更新部分页面内容

# 缺点
1. 存在跨域问题
2. 爬虫爬不到数据

二、基本案例

1. 后端node

  • 借助express搭建了一个服务端
let express = require('express');

let app = express();

app.listen(8081, '127.0.0.1', function () {
    console.log('Server Started Successfully');
})


/*一个get请求:
* http://127.0.0.1:8081/name */
app.get('/name', function (request, response) {
    /*解决跨域问题*/
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.send('Hello Ajax');
})

/* http://127.0.0.1:8081/info?name=shuzhan&age=1 */
app.get('/info', function (request, response) {
    /*解决跨域问题*/
    response.setHeader('Access-Control-Allow-Origin', '*');
    let query = request.query;
    let name = query.name;
    let age = query.age;
    response.send(`Hello, Ajax, Your Name is ${name}, Your age is ${age}`);
})

/*无参post: http://127.0.0.1:8081/update*/
app.post('/update', function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.send('Post Method without params')
})

/*带请求体post: http://127.0.0.1:8081/updateWithBody*/
app.post('/updateWithBody', function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');

    let data = {
        name: 'erick',
        age: 20,
        address: 'shanghai'
    }

    /*将对象以json的数据返回*/
    response.send(JSON.stringify(data));
})

2. get请求

如果是带参数,只需要再url中带参数即可:

 xhr.open('GET', 'http://127.0.0.1:8081/info?name=shuzhan&age=10');
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax-demo</title>

    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin-top: 50px;
        }
    </style>
</head>
<body>

<button>发送Ajax请求</button>
<div></div>

<script>
    let divElement = document.querySelector('div');

    let btn = document.querySelector('button');
    btn.addEventListener('click', function () {
        /*ajax请求*/
        /* 1. 创建一个对象,浏览器中的xhr: 就是具体的ajax请求*/
        let xhr = new XMLHttpRequest();
        /* 2. 初始化,设置请求方法和请求url, 本地的不要用localhost*/
        xhr.open('GET', 'http://127.0.0.1:8081/name');
        /* 3. 发送请求*/
        xhr.send();

        /* 4. 事件绑定,服务端获取后台后的数据处理
        *   4.1 readyState: 是xhr中的属性包含5个值
        *        0: 未初始化
        *        1: open方法调用完毕
        *        2: send方法调用完毕
        *        3: 服务端返回部分结果
        *        4: 服务端返回全部结果
        *   4.2 根据readyState的状态改变,会触发函数,一共会触发4次
        *     */
        xhr.onreadystatechange = function () {
            console.log('触发了一次。。。。。');

            /*服务端返回了所有数据的时候再去处理*/
            if (xhr.readyState !== 4) {
                /*如果响应成功*/
                if (xhr.status >= 200 && xhr.status < 300) {
                    /*返回的具体结果*/
                    let response = xhr.response;
                    divElement.innerHTML = response;
                }
            }
        }
    })
</script>
</body>
</html>

在这里插入图片描述

3. post请求

# 带请求体的话,只需要在send中传递
xhr.send('Hello, This is a request body');
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin-top: 50px;
        }
    </style>
</head>
<body>

<div></div>

<script>
    let div = document.querySelector('div');

    div.addEventListener('mouseover', function () {
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:8081/update');
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    div.innerHTML = xhr.response;
                }
            }
        }
    })
</script>
</body>
</html>

4. 自定义请求头

<script>
	xhr.setRequestHeader('name','erick');
	xhr.setRequestHeader('company','nike');
	xhr.setRequestHeader('address','shanghai');
</script>

5. 获取服务端的json数据

<script>

    /*如果后端返回的是一个json字符串,那么ajax默认收到的就是string类型的*/
    let div = document.querySelector('div');

    div.addEventListener('mouseover', function () {
        let xhr = new XMLHttpRequest();
        /*设置接受结果为json,  方便下面从response中获取对应的fields*/
        xhr.responseType = 'json';
        xhr.open('POST', 'http://127.0.0.1:8081/updateWithBody');
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let name = xhr.response.name;
                    let age = xhr.response.age;
                    let address = xhr.response.address;
                    div.innerHTML = name + age + address;
                }
            }
        }
    })
</script>

三、 Ajax进阶

1. 网络超时

后端代码

let express = require('express');

let app = express();

app.listen(8081, '127.0.0.1', function () {
    console.log('Server Started Successfully');
})

app.get('/name', function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');

    /*延时5秒后响应*/
    setTimeout(function (){
        response.send('Hello Ajax');
    },5000);
})

前端代码

<script>
    let divElement = document.querySelector('div');
    let btn = document.querySelector('button');

    btn.addEventListener('click', function () {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://127.0.0.1:8081/name');
        xhr.send();

        /*设置超时事件,如果超过,则取消本次请求*/
        xhr.timeout = 2000;

        /*请求超时后的回调函数*/
        xhr.ontimeout = function () {
            alert('Request Timeout, Please Retry');
        }

        xhr.onreadystatechange = function () {
            console.log('触发了一次。。。。。');
            if (xhr.readyState !== 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let response = xhr.response;
                    divElement.innerHTML = response;
                }
            }
        }
    })
</script>

2. 取消请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax-demo</title>

    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin-top: 50px;
        }
    </style>
</head>
<body>

<button>请求</button>
<button>取消</button>
<div></div>

<script>
    let divElement = document.querySelector('div');
    let btns = document.querySelectorAll('button');

    let xhr;
    /*请求的ajax*/
    btns[0].addEventListener('click', function () {
        xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://127.0.0.1:8081/name');
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let response = xhr.response;
                    divElement.innerHTML = response;
                }
            }
        }
    })

    btns[1].addEventListener('click', function () {
        /*取消请求*/
        xhr.abort();
        alert('Request Cancelled');
    })

</script>
</body>
</html>

3. 节流

  • 当用户在页面疯狂点击一个按钮的时候,会向服务端发送多次请求
  • 解决方法:第二次点击时候,如果前面的还在运行,那么取消第二次请求
<script>
    let divElement = document.querySelector('div');
    let btn = document.querySelector('button');

    let xhr;
    /* 节流器*/
    let isProceeding = false;

    btn.addEventListener('click', function () {
        if (isProceeding){
            return;
        }

        xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://127.0.0.1:8081/name');
        xhr.send();

        /*开始执行任务时候,变为true*/
        isProceeding = true;

        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let response = xhr.response;
                    divElement.innerHTML = response;
                    /*任务执行完毕后,置为false*/
                    isProceeding = false;
                }
            }
        }
    })
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值