• 初学AJAX:express框架基本使用、ajax处理get/post请求、请求超时与网络异常处理、取消请求操作


    初学AJAX

    1、AJAX的优点和缺点

    • 优点
      1)无需刷新页面而与服务器端进行通信
      2)允许根据用户事件来更新页面部分内容
    • 缺点
      1)没有浏览历史,不能回退
      2)存在跨域问题(同源)
      3)SEO不友好(SEO:搜索引擎优化)

    2、express框架基本使用

    简单来说就是:模拟后端服务器

    1、初始化

    npm init -y
    
    • 1

    2、下载安装express

    npm i express
    
    • 1

    3、基本使用
    express.js

    // 1、引入express
    const express = require('express')
    
    // 2、创建应用对象
    const app = express()
    
    // 3、创建路由规则,第一个参数是访问路径
    app.get('/',(request,response) => {
    	// 做出响应
        response.send('hello world')
    })
    
    // 4、监听端口,启动服务
    app.listen(8000,()=> {
        console.log('服务已经启动,8000端口监听中。。。');
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    注意,每次修改了express框架时都需要重新启动才会生效,这里推荐一个nodemon工具,可以做到每次修改express后自动启动服务
    步骤:
    安装: npm i nodemon
    使用:npx nodemon xxx.js
    在这里插入图片描述

    3、ajax处理get请求

    3.1 不传参

    • server.js模拟服务器
    // 引入express
    const { response } = require('express')
    const express = require('express')
    
    // 创建应用对象
    const app = express()
    
    // 创建路由规则
    app.get('/server',(request,response) => {
        // 设置响应头 允许跨域
        response.setHeader('Access-Control-Allow-Origin','*')
        // 设置响应
        response.send('hello ajax')
    })
    
    // 监听端口,启动服务
    app.listen(8000,() => {
        console.log("服务启动,监听8000端口中...");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 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>ajax get请求title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">div>
    
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                xhr.open('get','http://127.0.0.1:8000/server?a=100&b=200')
                xhr.send()
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >=200 && xhr.status<300){
                            // 响应行
                            console.log(xhr.status) // 状态码
                            console.log(xhr.statusText) // 状态字符串
                            console.log(xhr.getAllResponseHeaders()); // 所有响应头
                            console.log(xhr.response); // 响应体
    
                            // 设置文本
                            div.innerHTML = xhr.response;
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    在这里插入图片描述


    在这里插入图片描述
    在这里插入图片描述


    3.2 传参

    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>ajax get请求title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">div>
    
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                // 参数跟在url后面
                xhr.open('get','http://127.0.0.1:8000/server?a=100&b=200')
                xhr.send()
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >=200 && xhr.status<300){
                            // 响应行
                            console.log(xhr.status) // 状态码
                            console.log(xhr.statusText) // 状态字符串
                            console.log(xhr.getAllResponseHeaders()); // 所有响应头
                            console.log(xhr.response); // 响应体
    
                            // 设置文本
                            div.innerHTML = xhr.response;
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    4、ajax处理post请求

    4.1 传参

    • server.js
    // 引入express
    const { response } = require('express')
    const express = require('express')
    
    // 创建应用对象
    const app = express()
    
    // 创建路由规则
    app.post('/server',(request,response) => {
     	// 设置请求头:允许跨域
        response.setHeader('Access-Control-Allow-Origin','*')
        response.send('hello ajax')
    })
    
    // 监听端口,启动服务
    app.listen(8000,() => {
        console.log("服务启动,监听8000端口中...");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 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>ajax post请求title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">
    
        div>
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                xhr.open('post','http://127.0.0.1:8000/server')
                // 传参
                xhr.send('a=100&b=200')
                // xhr.send('a:100&b:200')
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status< 300){
                            div.innerHTML = xhr.response
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    结果:
    在这里插入图片描述

    4.2 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>ajax post请求title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">
    
        div>
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                xhr.open('post','http://127.0.0.1:8000/server')
                // 设置请求头,设置了数据发送类型的固定写法:'变量=值&变量=值'
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
                xhr.send('a=100&b=200')
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status< 300){
                            div.innerHTML = xhr.response
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    在这里插入图片描述

    后端处理请求头

    response.setHeader('Access-Control-Allow-Header','*') // 允许所有类型的请求头
    
    • 1
    • 其他常用的响应头

    发送json格式数据

    request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    
    • 1

    发送表单数据

    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
    
    • 1

    发送纯文本(不指定Content-type时,为默认值)

    request.setRequestHeader('Content-type', 'text/plain; charset=utf-8');
    
    • 1

    发送html文本

    request.setRequestHeader('Content-type', 'text/html; charset=utf-8');
    
    • 1

    5、服务器响应json格式数据

    • server.js
    // 引入express
    const { response } = require('express')
    const express = require('express')
    
    // 创建应用对象
    const app = express()
    
    // all表示请求方式可以为任意类型
    app.all('/server',(request,response) => {
        // 设置响应头
        response.setHeader('Access-Control-Allow-Origin','*') // 允许跨域
        // 响应一个数据
        const data = {
            name:'小红'
        }
        // 将这个对象转换为json字符串
        const str = JSON.stringify(data)
        // 设置响应,将这个数据作为响应返回
        response.send(str)
    })
    
    // 监听端口,启动服务
    app.listen(8000,() => {
        console.log("服务启动,监听8000端口中...");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 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>ajax post请求title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">
    
        div>
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                xhr.open('post','http://127.0.0.1:8000/server')
                // 设置请求头,设置了数据发送类型的固定写法:'变量=值&变量=值'	
                 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
                 
                // 方式二:自动数据转换:将服务器传过来的json字符串 => 原来数据类型
                // xhr.responseType = 'json';
                
                xhr.send('a=1&b=2')
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status< 300){
                            // 方式一:手动数据转换:json=>原来类型的数据
                            let data = JSON.parse(xhr.response)
                            
                            div.innerHTML = data.name
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    ajax-get请求方式也是这么处理,就不补充了

    6、ajax请求超时与网络异常处理

    描述:当页面刷新时间过久,还是没有显示出内容时的处理

    • server.js
    // 引入express
    const { response } = require('express')
    const express = require('express')
    
    // 创建应用对象
    const app = express()
    
    app.get('/server',(request,response) => {
        // 设置响应头
        response.setHeader('Access-Control-Allow-Origin','*')
        // 设置3s后响应
        setTimeout(()=>{
            response.send('hello')
        },3000)
    })
    // 监听端口,启动服务
    app.listen(8000,() => {
        console.log("服务启动,监听8000端口中...");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 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> 请求超时与网络异常处理title>
        <style>
            #decorate{
                width: 200px;
                height: 100px;
                border: dotted 3px pink;
            }
        style>
    head>
    <body>
        <button id="btn">发送button>
        <div id="decorate">
    
        div>
        <script>
            let btn = document.getElementById('btn')
            let div = document.getElementById('decorate')
            btn.onclick = function(){
                const xhr = new XMLHttpRequest()
                // 超时设置 
                xhr.timeout = 2000;
                // 超时回调:如果在2s内还没有拿到响应那么执行该回调
                xhr.ontimeout = function(){
                    alert('网络异常!请稍后再试!')
                }
    
                // 网络异常处理
                xhr.onerror = function(){
                    alert("你的网络似乎出了点问题...")
                }
    
                xhr.open('get','http://127.0.0.1:8000/server')
                xhr.send()
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status< 300){
                            div.innerHTML = xhr.response
                        }
                    }
                }
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    在这里插入图片描述

    7、取消请求

    主要方法:xhr.abort()方法
    实例:

    • server.js
    // 引入express
    const { response } = require('express')
    const express = require('express')
    
    // 创建应用对象
    const app = express()
    
    app.get('/server',(request,response) => {
        // 设置响应头
        response.setHeader('Access-Control-Allow-Origin','*')
        // 设置3s后响应
        setTimeout(()=>{
            response.send('hello')
        },3000)
    })
    // 监听端口,启动服务
    app.listen(8000,() => {
        console.log("服务启动,监听8000端口中...");
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 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>取消请求title>
    head>
    <body>
        <button>点击发送button>
        <button>点击取消button>
        <script>
            let btns = document.querySelectorAll('button')
            let x = null;
            // 发送请求
            btns[0].onclick = function(){
                x = new XMLHttpRequest()
                x.open('get','http://127.0.0.1:8000/server')
                x.send()
                // ...
            }
    
            // 取消请求
            btns[1].onclick = function(){
                x.abort();
            }
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    第十二章 旋转和横向运动
    Java 复习笔记 - 常见算法:查找算法
    Docker 入门:如何打包、部署并运行你的应用
    TiDB 集群监控部署
    2.Java怎么正确停止线程呢?
    Vue3 - 全局 API(相比 Vue2 有什么变化?具体怎么使用?)
    设计模式学习(十四):模板方法
    TinyRenderer学习笔记--从零构建软件渲染器
    倒圆角
    【冷知识】git头像设置
  • 原文地址:https://blog.csdn.net/lalala_dxf/article/details/125888116