前端同步发送HTTP请求 Ajax、Fetch和Axios实现HTTP同步请求

同步发送HTTP请求

同步发送HTTP请求,是指在发送请求后,程序会等待服务器响应并接收完整的响应数据后才会继续执行后续代码。

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>同步请求</title>
    <style>
        .container{
            margin: 0 auto;
            width: 400px;
            height: 300px;
            display:flex;
            flex-direction: column;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <div style="flex:1;background-color:coral">
            <button onclick="asyncAjax1()">Ajax同步请求1,用于判断资源是否存在~</button><br/>
            <button onclick="asyncAjax2()">Ajax同步请求2,直接返回内容~</button><br/>
            <button onclick="asyncFetch()">Fetch同步请求,直接返回内容~</button><br/>
            <button onclick="asyncAxios()">Axios同步请求,直接返回内容~</button>
        </div>
        <div id="output" style="flex:1;background-color: aqua;">
        </div>
    </div>
    <script type="text/javascript">
        function asyncAjax1(){
            console.log('asyncAjax1()');
            const url = '/index.html';
            try{
                var request = new XMLHttpRequest();
                // false表示同步
                request.open('GET', url, false);
                request.send(null);
                if (request.status === 200) {
                    // return true;
                    document.getElementById('output').innerHTML='success!';
                } else {
                    // return false;
                }
            }catch (e){
                console.log('错误:',e);
                // return false;
            }
        }
        asyncAjax2 = () => {
            console.log('asyncAjax2()');
            const url = '/api/demo/demo01';
            let content = '';
            try{
                var xhRequest = new XMLHttpRequest();
                xhRequest.open('POST', url, false);
                xhRequest.setRequestHeader("Content-Type", "application/json");
                var data = JSON.stringify({
                    key: "value"
                });
                xhRequest.send(data);
                if (xhRequest.readyState === 4 && xhRequest.status === 200) {
                    content = xhRequest.responseText;
                } 
            }catch (e){
                console.log('错误:',e);
            }
            document.getElementById('output').innerHTML=content;
        }
        asyncFetch = async ()=>{
            console.log('asyncFetch()');
            const url = '/api/demo/demo01';
            let content = '';
            try{
                const response = await fetch(url, {
                        method: 'POST', // 或 'GET'
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            key: 'value'
                        }),
                    });
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                // console.log(await response.text());
                content = JSON.stringify(await response.json());
                
            }catch(e){
                console.log('错误:',e);
            }
            document.getElementById('output').innerHTML=content;
        }
        asyncAxios = async ()=>{
            console.log('asyncAxios()');
            const url = '/api/demo/demo01';
            let content = '';
            try {
                const response = await axios.post(url, {key: 'value'});
                content = JSON.stringify(response.data);
            } catch (e) {
                console.log('错误:',e);
            }
            document.getElementById('output').innerHTML=content;
        }
    </script>
</body>
</html>
相关推荐
晴殇i1 分钟前
for...in 循环的坑,别再用它遍历 JavaScript 数组了!
前端·javascript
littleplayer3 分钟前
iOS 单元测试详细讲解-DeepSeek
前端
异常君4 分钟前
HTTP头中的Accept-Encoding与Content-Encoding深度剖析
后端·nginx·http
littleplayer4 分钟前
iOS 单元测试与 UI 测试详解-DeepSeek
前端·单元测试·测试
夜熵7 分钟前
Vue中nextTick()用法
前端·面试
小桥风满袖7 分钟前
Three.js-硬要自学系列15 (圆弧顶点、几何体方法、曲线简介、圆、椭圆、样条曲线、贝塞尔曲线)
前端·css·three.js
洋流8 分钟前
JavaScript事件流机制详解:捕获、冒泡与阻止传播
前端·javascript
啊花是条龙8 分钟前
在 Angular 中使用 ECharts 并处理 xAxis 标签的点击事件
前端·angular.js
凌冰_13 分钟前
CSS3 基础(背景-文本效果)
前端·css·css3
tjh000114 分钟前
vue3+TS 手动实现表格滚动
前端·javascript·vue.js