• 前端js调用后端API获取数据的三种方法(2022.7.25)


    前言

            随着云计算分布式微服务技术的发展,现有网络项目大都基于前后端分离的技术手段实施,一方面是便于缓解后台服务器的压力,充分利用各台服务节点的计算和存储资源,尽可能地提高服务器性能;另一方面可提高服务的可靠性、容灾能力,以便在某服务节点上服务器甚至节点崩溃的情况下得以对该服务快速有效地进行替换或恢复,表现为极强的修复能力(注:先进制造技术的发展和充足的材料供应能力使得时间、价格方面的维修成本不断高于替换成本,让废旧品及时得到回收利用再生产,从而减少繁琐的维修过程,以便缩短维修时间,即能换不修原则)。
            在Web项目实施的过程中,后端工程师负责发布Web服务,提供完善的调用接口;而前端开发人员则以后台服务接口的说明文档为基础,按需调用后台API来实现数据的接收,最后利用可视化技术对数据进行炫酷展示,进而提供强大的平台功能

    需求分析

            在Web前端开发的过程中,javascript 工程师开发人员往往需要调用后台API来获取所需数据(data),之后通过向菜单、列表、表格、文本框、按钮、下拉框div内部控件中填充显示,从而实现网页系统的展示、查询和动态更新等目标。当然,前端开发者和后台工程师皆可通过PostmanSoapUI等软件来测试接口是否正常和能否返回数据,或者自己编写Java代码来发送http请求,最常用的非DevTools莫属。

            下图是网上的一个后台API实例,它利用Swagger在线文档说明了多个后台接口的调用方法,较为详细,实测有效,通过此实例来证明本文所述三种方法的可行性和有效性。

    网上的一个后台API在线文档

    一个Get实例

            http://112.125.90.247:81/api/Log4Net/GetAsync?page=1&intPageSize=20,此Get类型的url是一个典型的单页查询接口,用于获取HTML文档中分页表格第1页中的20条数据记录,通过修改pageintPageSize的大小然后发送Get类型的Http请求主动获取响应数据得以动态更新前端页面表格。

    浏览器请求

    在这里插入图片描述

    SoapUI软件请求

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

    一个Post实例

    url: "http://112.125.90.247:81/api/Data/Post",
    data: {
        "Id": "string",
        "Name": "string",
        "X": 123,
        "Y": 456,
        "Num": 0,
        "Note": "string",
        "Attachment": "string",
        "CreateTime": "2022-07-19T15:33:28.504Z",
        "UpdateTime": "2022-07-19T15:33:28.504Z"
    },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

            此Post实例对应的urlhttp://112.125.90.247:81/api/Data/Post,需要向其发送的数据字段共有9个,分别是Id、Name、X、Y、Num、Note、Attachment、CreateTime、UpdateTime,Post类型的请求需要将其嵌入到XML请求进行发送,之后获取XML响应并解析结果得到所需的返回数据。

    浏览器请求

            如果将上述请求封装为Get类型的请求,则对应urlhttp://112.125.90.247:81/api/Data/Post?Id=String&Name=string&X=123&Y=456&Num=0&Note=string&Attachment=string&CreateTime=2022-07-19T15:33:28.504Z&UpdateTime=2022-07-19T15:33:28.504Z,将其在浏览器地址栏中打开,提示如下信息:请求的资源不支持http方法"GET",这就说明此Post类型的后台API接口在开发时明确了不支持Get方式访问,但有的Post接口是支持Get方法访问的,因为在后端可进行配置

    在这里插入图片描述

    SoapUI软件请求

    在这里插入图片描述

    1、Http简介(Browser / Server)

            HTTP一般指HTTP 协议(超文本传输协议,即HyperText Transfer Protocol的缩写),是因特网上应用最为广泛的一种网络传输协议。作为一种用于分布式、协作式和超媒体信息系统的应用层协议,HTTP 是为 Web 浏览器Web 服务器之间的通信而设计的,它基于 TCP/IP 通信协议来传递HTML*文件、图片、文本、视频、、音频、查询结果等数据。

    1.1 六个主流的浏览器

    Chrome
    Edge
    Firefox
    Internet Explorer
    Opera
    Safari
    各大浏览器

            B/S类型的Web项目需要依靠网页浏览器来展示前端网页平台效果,而各个浏览器因版本和内核的不同所对应的的兼容性支持能力也不尽相同,而从用户体验而言,目前业界内使用次数较多和受到一致好评的浏览器当属——Google公司推出的Chrome网页浏览器

    1.2 HTTP请求(Get & Post)

            HTTP请求是指从Client端到Server端的请求消息,通常是对资源进行请求,需要设定资源的请求方法Method资源的标识符Identifier使用的协议Protocol及版本Version,然后向Web服务器发送数据块(即请求信息)。HTTP请求包含多种方法,最常用的为Get方式Post方式,下表对这两种方式进行了简单对比。

    GetPost
    参数在URL参数放在请求体
    发送数据量小发送数据量大
    安全性低,会被缓存安全性高,不会缓存
    Http请求中Get方式和Post方式的对比

    2、JavaScript简介

            JavaScript作为动态客户端脚本语言,可提供网页内容的动态更新、地图交互、二三维图形动画展示、视频播放及点唱机滚动等效果,简而言之,HTMLCSS仅能够提供静态页面,就是对静态的网页信息实现动态化

    JavaScript官网
    Github上的JavaScript

    3、前端js调用后端API的三种方法

    下面主要介绍三种方法来实现前端js对后端API接口的调用:
    方法一XMLHttpRequest
    方法二jQuery和Ajax
    方法三axios

    3.1 XMLHttpRequest(无需引入外部库)

            随着XMlHttpRequest对象的广泛采用,开发者可以快速构建如 Google MapsGmail 这样的 Web 应用程序,这些应用程序使用 XMLHttpRequest 来获取新的地图图块或新的电子邮件,而无需重新加载整个页面。使用XMLHttpRequest的步骤为:(1)创建XMLHttpRequest对象;(2)建立http连接;(3)发送请求;(4)获取返回数据
            Post请求与Get请求主要有两点不同:
    post请求需要设置请求头的格式内容:xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    post请求参数放在send里面,即请求体。具体详情可参考mozilla-xmlhttprequestGithub上对xmlhttprequest的有关介绍。
    在这里插入图片描述
    在这里插入图片描述

    3.1.1 get实例(XHR)

    3.1.1.1 xhr-get.html

    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var pageid = document.getElementById("pageid").value;
                    var pagesize = document.getElementById("pagesize").value;
                    if(!isNaN(Number(pageid)) && !isNaN(Number(pagesize))){
                        var xmlhttp,url="http://112.125.90.247:81/api/Log4Net/GetAsync?page="+pageid+"&intPageSize="+pagesize;
                        if (window.XMLHttpRequest){
                            xmlhttp = new XMLHttpRequest();//  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                        }
                        else{
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");// IE6, IE5 浏览器执行代码
                        }
                        xmlhttp.onreadystatechange=function(){
                            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                                responsecontent = xmlhttp.responseText;
                                var Res = "成功获取HTTP响应,得到第"+pageid+"页共"+pagesize+"个结果!\n"+responsecontent;
                                document.getElementById("result").innerText = Res;
                                document.getElementById("convertjson").disabled = false;
                                document.getElementById("jsonresult").innerText = "";
                            }
                        }
                        xmlhttp.open("GET",url,true);
                        xmlhttp.send();
                    }else{
                        window.alert("请输入整数!");
                        document.getElementById("result").innerText = "";
                        document.getElementById("convertjson").disabled = true;
                        responsecontent = "";
                    }
    
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <form style="color:#2572adfa;border:2px">
                    <label>请输入页数(如5)label><input type="text" value="5" id="pageid"/><br>
                    <label>请输入页面大小(15)label><input type="text" value="15" id="pagesize"/>
                form>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99

    3.1.1.2 xhr-get.html运行结果

    在这里插入图片描述

    3.1.2 post实例( XHR)

    3.1.2.1 xhr-post.html

    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var xmlhttp,url="http://112.125.90.247:81/api/Data/Post";
                    if (window.XMLHttpRequest){
                        xmlhttp = new XMLHttpRequest();//  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                    }
                    else{
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");// IE6, IE5 浏览器执行代码
                    }
                    xmlhttp.onreadystatechange=function(){
                        if (xmlhttp.readyState==4 && xmlhttp.status==200){
                            responsecontent = xmlhttp.responseText;
                            var Res = "成功获取HTTP响应,得到结果!\n"+responsecontent;
                            document.getElementById("result").innerText = Res;
                            document.getElementById("convertjson").disabled = false;
                            document.getElementById("jsonresult").innerText = "";
                        }
                    }
                    xmlhttp.open("POST",url,true);
                    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");// Post请求需要设置请求头
                    xmlhttp.send("Id="+"string"+"&Name="+"string"+"&X="+"123"+"&Y="+"456"+"&Num="+"0"+"&Note="+"string"+"&Attachment="+"string"+"&CreateTime="+"2022-07-19T15:33:28.504Z"+"&UpdateTime="+"2022-07-19T15:33:28.504Z");
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    3.1.2.2 xhr-post.html 运行结果

    在这里插入图片描述

    3.2 jQuery或Ajax(引入jQuery库)

    3.2.1 jQuery简介

            作为一个 JavaScript 库,jQuery使得JavaScript编程十分简单,拥有write less, do more的响亮口号,十分注重实际行动和用户体验。关于jQuery的使用,一方面,可以下载jQuery文件html文件中进行本地引用,或者直接引用带url链接的在线jQuery.js文件;另一方面,可以使用Node包管理工具npm进行命令行安装npm install jquery

    3.2.1.1 get实例(jQuery)

    3.2.1.1.1 jQuery-get.html
    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var pageid = document.getElementById("pageid").value;
                    var pagesize = document.getElementById("pagesize").value;
                    if(!isNaN(Number(pageid)) && !isNaN(Number(pagesize))){
                        var url="http://112.125.90.247:81/api/Log4Net/GetAsync?page="+pageid+"&intPageSize="+pagesize;
                        $.get(url).done(function (res) {
                            console.log(res);
                            responsecontent = JSON.stringify(res.response.data);
                            var Res = "成功获取HTTP响应,得到第"+pageid+"页共"+pagesize+"个结果!\n"+responsecontent;
                                document.getElementById("result").innerText = Res;
                                document.getElementById("convertjson").disabled = false;
                                document.getElementById("jsonresult").innerText = "";
                        }).fail(function (e) {
                            console.log('error');
                        })
                    }else{
                        window.alert("请输入整数!");
                        document.getElementById("result").innerText = "";
                        document.getElementById("convertjson").disabled = true;
                        responsecontent = "";
                    }
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <form style="color:#2572adfa;border:2px">
                    <label>请输入页数(如5)label><input type="text" value="5" id="pageid"/><br>
                    <label>请输入页面大小(15)label><input type="text" value="15" id="pagesize"/>
                form>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    3.2.1.1.2 jQuery-get.html 运行结果

    在这里插入图片描述

    3.2.1.2 post实例(jQuery)

    3.2.1.2.1 jQuery-post.html
    
    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var url="http://112.125.90.247:81/api/Data/Post";
                    $.post(url,
                    {
                        "Id": "string",
                        "Name": "string",
                        "X": 1234,
                        "Y": 4567,
                        "Num": 0,
                        "Note": "string",
                        "Attachment": "string",
                        "CreateTime": "2022-07-19T15:33:28.504Z",
                        "UpdateTime": "2022-07-19T15:33:28.504Z"
                    }).done(function(res){
                        alert("数据: " + JSON.stringify(res));
                        responsecontent = JSON.stringify(res);
                        var Res = "成功获取HTTP响应如下: "+"\n"+responsecontent;
                        document.getElementById("result").innerText = Res;
                        document.getElementById("convertjson").disabled = false;
                        document.getElementById("jsonresult").innerText = "";
                    });
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    3.2.1.2.2 jQuery-post.html 运行结果

    在这里插入图片描述

    3.2.2 Ajax简介及使用

            Ajax的全称为Asynchronous JavaScript and XML异步 JavaScript 和 XML,它的作用是在无需刷新整个页面的条件下,通过与远端服务器交换数据来实现网页内容的局部更新,优点是能够提高用户体验,较少网络数据的传输量
            XMLHttpRequest 对象是Ajax技术的一部分。使用 Ajax可以调用XMLHttpRequest API 在浏览器和服务器之间传递数据,而无需重新加载网页。Ajax请求数据最核心的依赖是浏览器提供的XMLHttpRequest对象,因为请求是异步的,可以让浏览器发出HTTP请求与接收HTTP响应,同时接着做其他事情,等收到XHR返回来的数据再对页面进行渲染。然而,各种浏览器以不同的方式来实现 Ajax API,这就意味着开发人员在编写代码时要考虑不同浏览器的兼容性,以确保 Ajax 可以通用。不过,jQueryAjax 支持,提供了功能齐全的 $.ajax() 方法,能够直接调用。大多数的 jQueryAjax应用程序实际上并不使用 XML,反而将数据传输为纯 HTMLJSON
            另外,尽管Ajax 不能跨域工作,如由于违反了同源策略而无法从 example1.com 加载的网页向 example2.com 发出 Ajax 请求。作为一种解决方法,JSONP通过在html中使用script标签从另一个域加载包含任意 JavaScript 内容和 JSON 的文件。同时浏览器也实现了一种称为跨域资源共享 (CORS) 的技术,该技术也允许 Ajax 请求到不同的域。

    3.2.2.1 get实例(ajax)

    3.2.2.1.1 ajax-get.html
    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var pageid = document.getElementById("pageid").value;
                    var pagesize = document.getElementById("pagesize").value;
                    if(!isNaN(Number(pageid)) && !isNaN(Number(pagesize))){
                        // Using the core $.ajax() method
                        $.ajax({      
                            url: "http://112.125.90.247:81/api/Log4Net/GetAsync",// The URL for the request
                            data: { page: pageid, intPageSize: pagesize },// The data to send (will be converted to a query string)
                            type: "GET",// Whether this is a POST or GET request
                        }).done(function( res ) {
                            responsecontent = JSON.stringify(res.response.data);
                            var Res = "成功获取HTTP响应,得到第"+pageid+"页共"+pagesize+"个结果!\n"+responsecontent;
                            document.getElementById("result").innerText = Res;
                            document.getElementById("convertjson").disabled = false;
                            document.getElementById("jsonresult").innerText = "";
                        });
                    }else{
                        window.alert("请输入整数!");
                        document.getElementById("result").innerText = "";
                        document.getElementById("convertjson").disabled = true;
                        responsecontent = "";
                    }
    
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <form style="color:#2572adfa;border:2px">
                    <label>请输入页数(如5)label><input type="text" value="5" id="pageid"/><br>
                    <label>请输入页面大小(15)label><input type="text" value="15" id="pagesize"/>
                form>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    3.2.2.1.2 ajax-get.html 运行结果

    在这里插入图片描述

    3.2.2.2 post实例(ajax)

    3.2.2.2.1 ajax-post.html
    
    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    // Using the core $.ajax() method
                    $.ajax({      
                        url: "http://112.125.90.247:81/api/Data/Post",// The URL for the request
                        data: {
                            "Id": "string",
                            "Name": "string",
                            "X": 123,
                            "Y": 456,
                            "Num": 0,
                            "Note": "string",
                            "Attachment": "string",
                            "CreateTime": "2022-07-19T15:33:28.504Z",
                            "UpdateTime": "2022-07-19T15:33:28.504Z" 
                            },// The data to send (will be converted to a query string)
                        type: "POST",// Whether this is a POST or GET request
                    }).done(function( res ) {
                        responsecontent = JSON.stringify(res);
                        var Res = "成功获取HTTP响应(如下):"+"\n"+responsecontent;
                        document.getElementById("result").innerText = Res;
                        document.getElementById("convertjson").disabled = false;
                        document.getElementById("jsonresult").innerText = "";
                    });
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    3.2.2.2.2 ajax-post.html 运行结果

    在这里插入图片描述

    3.3 axios(引入axios库)

            axios是一个简洁、易用且高效的http库,本质上也封装成了js库,在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。对于axios的使用,一方面,可通过在html文件中利用script标签进行本地或在线引入js文件进行调用;另一方面,如果使用Nodejs开发Web项目,则通过Node包管理工具npm进行命令行安装npm install axios

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
    • 1

    或者

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    • 1

    3.3.1 get实例(axios)

    3.3.1.1 axios-get.html

    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://unpkg.com/axios/dist/axios.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    var pageid = document.getElementById("pageid").value;
                    var pagesize = document.getElementById("pagesize").value;
                    if(!isNaN(Number(pageid)) && !isNaN(Number(pagesize))){
                        axios({
                            method: 'get',
                            url: "http://112.125.90.247:81/api/Log4Net/GetAsync?page="+pageid+"&intPageSize="+pagesize
                        })
                        .then(function (response) {
                            responsecontent = JSON.stringify(response.data.response.data);
                            var Res = "成功获取HTTP响应,得到第"+pageid+"页共"+pagesize+"个结果!\n"+responsecontent;
                            document.getElementById("result").innerText = Res;
                            document.getElementById("convertjson").disabled = false;
                            document.getElementById("jsonresult").innerText = "";
                        });
                    }else{
                        window.alert("请输入整数!");
                        document.getElementById("result").innerText = "";
                        document.getElementById("convertjson").disabled = true;
                        responsecontent = "";
                    }
    
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <form style="color:#2572adfa;border:2px">
                    <label>请输入页数(如5)label><input type="text" value="5" id="pageid"/><br>
                    <label>请输入页面大小(15)label><input type="text" value="15" id="pagesize"/>
                form>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    3.3.1.2 axios-get.html 运行结果

    在这里插入图片描述

    3.3.2 post实例(axios)

    3.3.2.1 axios-post.html

    DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>HTML页面测试XHR请求 By jing_zhongtitle>
            <script src="https://unpkg.com/axios/dist/axios.min.js">script>
            <script>
                //获取系统当前时间的函数
                function gettime(){
                    var a = new Date();
                    var b = a.toLocaleTimeString();
                    var c = a.toLocaleDateString();
                    document.getElementById("currenttime").innerHTML = c+" "+b +" By jing_zhong";
                }
                setInterval(function() {gettime()},1000);
                var responsecontent;
                //发送HTTP请求的函数
                function SendXMLHttpRequest() {
                    axios({
                        method: 'post',
                        url: "http://112.125.90.247:81/api/Data/Post",
                        data: {
                            "Id": "string",
                            "Name": "string",
                            "X": 123,
                            "Y": 456,
                            "Num": 0,
                            "Note": "string",
                            "Attachment": "string",
                            "CreateTime": "2022-07-19T15:33:28.504Z",
                            "UpdateTime": "2022-07-19T15:33:28.504Z"
                        },
                        //baseURL: 'http://112.125.90.247:81/',//http://112.125.90.247:81/api/Data/Post
                        timeout: 1000,
                        headers: {'Content-Type':'application/x-www-form-urlencoded'}
                    }).then(function (response) {
                        responsecontent = JSON.stringify(response.data);
                        var Res = "成功获取HTTP响应,得到结果!\n"+responsecontent;
                        document.getElementById("result").innerText = Res;
                        document.getElementById("convertjson").disabled = false;
                        document.getElementById("jsonresult").innerText = "";
                    }).catch(function(error){
                        console.log('error:' + error);
                    })
                }
                //对json数据进行高亮的函数
                function syntaxHighlight(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '+ cls + '">' + match + '';
                    });
                }
                //将请求结果转为json格式的函数
                function ToJSON() {
                    console.log(responsecontent);
                    var Res = JSON.parse(responsecontent, null, 3);
                    document.getElementById("jsonresult").innerHTML = syntaxHighlight(Res);
                }
            script>
            <style>
                pre { background-color:rgb(238, 231, 231); outline: 1px solid #ccc; padding: 5px; margin: 5px; }
                .string { color: rgb(22, 10, 126); }
                .number { color: rgb(13, 214, 124); }
                .boolean { color: rgb(225, 97, 195); }
                .null { color: rgb(172, 167, 14); }
                .key { color: #cf4914; }
                #myDiv { background-image: url("https://img2.baidu.com/it/u=1721953618,4133119400&fm=253&fmt=auto&app=138&f=JPEG");}
            style>
        head>
        <body>
            <div id="myDiv">
                <label id="currenttime" style="color: #AC2925; ">label>
                <button type="button" onclick="SendXMLHttpRequest()">1、利用XMLHttpRequest发送请求button>
                <p id="result" style="color:#b0a117fa">p>
                <button type="button" disabled="false" onclick="ToJSON()" id="convertjson">2、将请求结果转为json格式button>
                <pre id="jsonresult" class="pre">pre>
            div>
        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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94

    3.3.2.2 axios-post.html 运行结果

    在这里插入图片描述

    4、总结

            XMLHttpRequest是浏览器所支持原生js的方法,可直接调用;而jQuery和Ajax均需要依赖jQurey库;而axios多用于Nodejs管理的VueReact等项目中,作为典型的前后端分离API调用,通常需要处理跨域请求问题,针对跨域问题的解决办法在axios官网都有详细介绍,此处不再赘述。当axios用于html中进行Post请求,需要注意设置headers参数以得到成功的请求结果,亲身实践,多多感悟😁😁😁!!!

    未设置header参数而报错
    设置header参数headers: {'Content-Type':'application/x-www-form-urlencoded'}

    所用后台API实例来源于网络,仅供个人学习和研究其设计思想而交流使用,切勿频繁调用和非法商用

  • 相关阅读:
    Python生成器
    Redis缓存的高并发问题
    wirehark数据分析与取证misc1.pcap
    AI电话机器人有没有效果?具体的功能都有哪些?
    【超简单-Java设计模式2】简单工厂模式
    论文解读(DAGNN)《Towards Deeper Graph Neural Networks》
    团建游戏------踩数字
    CF1427F-Boring Card Game【贪心】
    linux小妙招(对比不同文件夹下的内容、kill掉后台运行的gdb进程)
    ROG幻15电脑开机自动安装软件怎么U盘重装系统
  • 原文地址:https://blog.csdn.net/jing_zhong/article/details/125698666