JavaScript,原生、jQuery、Axios,发送Ajax同步及异步请求代码

JavaScript/前端
133
0
0
2023-11-22
标签   Ajax Axios

说明

Web数据交互方式,Ajax:

Ajax,Asynchronous Javascript And XML(异步Java script 和XML),2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的新方法,包括: HTML 或XHTML, CSS ,JavaScript, DOM ,XML, XSLT ,以及最重要的XMLHttpRequest。 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。

jQuery

jQuery是一个快速、简洁的JavaScript框架,是继 Prototype 之后又一个优秀的JavaScript代码库(框架)于2006年1月由 John Resig 发布。封装了JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

Axios

一个基于promise的HTTP库,可以用在浏览器和 node.js 中。

跨域资源共享( CORS )

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。允许浏览器向跨源服务器,发出 xmlHttp Request请求,从而克服了AJAX只能同源使用的限制。

代码案例

原生的Ajax同步&异步代码案例

 //Ajax Get 同步请求
function AjaxSynGet(url) {
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //IE
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // xmlHttp.set Request Header("headName", "headName");
    xmlHttp.open("GET", url + '&rnd=' + Math.random(), false);
    xmlHttp.setRequestHeader("token","header-token-value");
    xmlHttp.send(null);
    var text = xmlHttp.responseText;
    return text;
}

//Ajax Post 同步请求
function AjaxSynPost(url, param) {
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //IE
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.open("POST", url + '&rnd=' + Math.random(), false);
    xmlHttp.setRequestHeader("token","header-token-value");
    xmlHttp.setRequestHeader("headName", 'headValue');
    xmlHttp.send(param);
    var text = xmlHttp.responseText;
    return text;
}

//Ajax Get 异步请求
// rtnFun: 函数
function AjaxGet(url, rtnFun) {
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //IE
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttp != null) {
        //get
        xmlHttp.open("GET", url + '&rnd=' + Math.random(), true);
        xmlHttp.setRequestHeader("token","header-token-value");
        xmlHttp.send(null);
        xmlHttp.onready state change = function() {
            // = "loaded"
            if (xmlHttp.readyState ==) {
                // = OK
                if (xmlHttp.status ==) {
                    var text = xmlHttp.responseText;
                    rtnFun(text);
                }
            }
        }
    }
}

//Ajax Post 异步请求
// rtnFun: 函数
function AjaxPost(url, param, rtnFun) {
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
        //IE
    } else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlHttp != null) {
        xmlHttp.open("POST", url + '&rnd=' + Math.random(), true);
        xmlHttp.setRequestHeader("token","header-token-value");
        xmlHttp.setRequestHeader("headName", 'headValue');
        xmlHttp.send(param);
        xmlHttp.onreadystatechange = function() {
            // = "loaded"
            if (xmlHttp.readyState ==) {
                // = OK
                if (xmlHttp.status ==) {
                    var text = xmlHttp.responseText;
                    rtnFun(text);
                }
            }
        }
    }
} 
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta  charset ="UTF-8">
    <title>原生的Ajax同步&异步代码案例</title>
    <!--r为参数防止浏览器缓存 -->
    <script type="text/javascript" src="ajax.js?r="></script>
</head>
<body>
    <div>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
    </div>
    <script type="text/javascript">
        //、Ajax Get同步请求
        let result = AjaxSynGet("#34;");
        console.log("result",result1);
        document.getElementById("result").innerText=result1;

        //、Ajax Post 同步请求
        let result = AjaxSynPost("#34;,"key=value");
        console.log("result",result2);
        document.getElementById("result").innerText=result2;

        //、Ajax Get 异步请求
        console.log("请求前:" + new Date().getTime());
        AjaxGet("#;, function(data){
            console.log("result",data);
            document.getElementById("result").innerText=data;
        });
        console.log("请求后:" + new Date().getTime());

        //、Ajax Ajax Post 异步请求
        console.log("请求前:" + new Date().getTime());
        AjaxPost("#;, "key=value", function(data){
            console.log("result",data);
            document.getElementById("result").innerText=data;
        });
        console.log("请求后:" + new Date().getTime());
    </script>
</body>
</html> 

jQuery的Ajax同步&异步代码案例

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-">
    <title>jQuery的Ajax同步&异步代码案例</title>
    <script src="#;></script>
</head>
<body>
    <div>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
    </div>
    <script type="text/javascript">
        //、Ajax Get同步请求
        let result = $.ajax({
            type: 'get',
            url: '#;,
            async:false,
            headers:{'token':''},
        });
        console.log("result",result1.responseText);
        $("#result").text(result1.responseText);

        //、Ajax Post 同步请求
        let result = $.ajax({
            type: 'post',
            url: '#;,
            data: {},
            async:false,
            headers:{'token':''},
        });
        console.log("result",result2.responseText);
        $("#result").text(result2.responseText);

        //、Ajax Get 异步请求
        $.get("#;, function(data,status){
            console.log("result",  JSON .stringify(data));
            $("#result").text(JSON.stringify(data));
        });
        $.ajax({
            type: 'get',
            url: '#;,
            async: true,
            headers:{'token':''},
            success: function (res){
                console.log("result", JSON.stringify(res));
                $("#result").text(JSON.stringify(res));
            },
            error:function(err){
                console.log("error",  err );
            }
        });

        //、Ajax AjaxPost 异步请求
        $.post("#;,{ id:''},function(data){
            console.log("result", JSON.stringify(data));
            $("#result").text(JSON.stringify(data));
        });
        $.ajax({
            type: 'post',
            url: '#;,
            data:{ id:'' },
            contentType: 'application/x-www-form-urlencoded',
            async: false,
            headers:{'token':''},
            success: function (res){
                console.log("result", JSON.stringify(res));
                $("#result").text(JSON.stringify(res));
            },
            error:function(err){
                console.log("error", err);
            }
        });
    </script>
</body>
</html> 

Axios的Ajax同步&异步代码案例

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-">
        <title>Axios的Ajax同步&异步代码案例</title>
        <script src="#;></script>
    </head>
<body>
    <div>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
        <hr/>
        <span id="result"></span>
    </div>
    <script type="text/javascript">
        // URL编码  URL解码
        console.log("URL编码",encode URI Component("名字"));
        console.log("URL解码", decode URIComponent("%E5%90%8D%E5%AD%97"));

        //、Ajax Get异步请求
        axios.get('名字',{
             params : {desc:"描述"},
            headers: {"token": "token"}
        }).then(res => {
            console.log("result", JSON.stringify(res.data));
            document.getElementById("result").innerText = JSON.stringify(res.data);
        });
        // 另外一种写法
        axios({
            url: '名字',
            method: 'GET',
            params: {desc:"描述"},
            headers: {"token": "token"}
        }).then(res => {
            console.log("result", JSON.stringify(res.data));
            document.getElementById("result").innerText = JSON.stringify(res.data);
        })

        //、Ajax Post异步请求
        axios.post('#;,"id=21&name=名字",{
            headers: {"token": "token"}
        }).then(res => {
            console.log("result", JSON.stringify(res.data));
            document.getElementById("result").innerText = JSON.stringify(res.data);
        })
        // 另外一种写法
        axios({
            url: '#;,
            method: 'post',
            data: {id:,name:'名字'},
            headers: {"token": "token"}
        }).then(res => {
            console.log("result", JSON.stringify(res.data));
            document.getElementById("result").innerText = JSON.stringify(res.data);
        });

        //、Ajax Get同步请求
        console.log("请求前:" + new Date().getTime());
        async function getData() {
            let data = "";
            await axios.get('名字').then(res => {
                data =  JSON.stringify(res.data);
                console.log("执行:" + new Date().getTime());
            });
            console.log("执行:" + new Date().getTime());
            return data;
        }
        const result = getData();
        result.then(res=>{
            console.log("执行:" + new Date().getTime());
            console.log("result", res);
            document.getElementById("result").innerText = res;
        })
        console.log("请求后:" + new Date().getTime());
    </script>
</body>
</html> 

SpringBoot后台代码

跨域的Filter:

 import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
        response.setHeader("Access-Control-Max-Age", "");
        //response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        response.setHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

} 

配置(主要是跨域):

 import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CommonConfig {

    @Bean
    public FilterRegistrationBean registerAuthFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new SimpleCORSFilter());
        registration.addUrlPatterns("/*");
        registration.setName("simpleCORSFilter");
        registration.setOrder();  // 值越小,Filter越靠前。
        return registration;
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); //允许任何域名
        corsConfiguration.addAllowedHeader("*"); //允许任何头
        corsConfiguration.addAllowedMethod("*"); //允许任何方法
        return corsConfiguration;
    }

    // @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); //注册
        return new CorsFilter(source);
    }

}

Controller支持:

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/data")
public class DataController {

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseBody
    public Object get(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("id", new Random().nextInt());
        dataMap.put("name", "富豪");
        dataMap.put("type", "GET");
        return dataMap;
    }

    @RequestMapping(value = "/post", method = RequestMethod.POST)
    @ResponseBody
    public Object post(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("id", new Random().nextInt());
        dataMap.put("name", "富豪");
        dataMap.put("type", "POST");
        return dataMap;
    }

}