当前位置: 首页 > article >正文

前端同步发送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>


http://www.kler.cn/a/469445.html

相关文章:

  • YOLOv5部署到web端(flask+js简单易懂)
  • 第27天:Web开发-PHP应用原生语法全局变量数据接受身份验证变量覆盖任意上传
  • 谷歌浏览器的安全检测工具使用指南
  • 开源复刻 | Matlab实现蚁狮优化算法ALO优化Transformer-LSTM实现负荷数据回归预测
  • Sql中WITH的作用
  • pygame飞机大战
  • SpringMVC(二)原理
  • 【QT】C++线程安全的单例模板
  • Docker容器中Elasticsearch内存不足问题排查与解决方案
  • 【车载网络】BUSOFF状态简述和制造
  • Go语言的 的输入/输出流(I/O Streams)核心知识
  • LeetCode:700.二叉搜索树中的搜索
  • ThreadLocal` 的工作原理
  • Apache zookeeper集群搭建
  • Java-数据结构-时间和空间复杂度
  • Python 标准库:hashlib——安全哈希与消息摘要
  • ARM CCA机密计算安全模型之加密建议
  • 26 go语言(golang) - GC原理
  • 系统架构师考试-MDA模型驱动架构
  • Mac 版本向日葵退出登录账号