Ajax-POST封装

本文不涉及然和的介绍和其它的相关内容,只是博主简单的记录一下封装 POST 的代码:

myAjax.js:

const obj2str = (obj) => {
    // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
    obj = obj || {};
    obj.t = new Date().getTime();
    let res = [];
    for (let key in obj) {
        // 在URL中是不可以出现中文的, 如果出现了中文需要转码
        // 可以调用encodeURIComponent方法
        // URL中只可以出现字母/数字/下划线/ASCII码
        res.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
    }
    return res.join("&");
}

const ajax = (type, url, obj, timeout, success, error) => {
    // 0.将对象转换为字符串
    // key=value&key=value;
    let str = obj2str(obj);

    // 1.创建一个异步对象
    let xmlHttp, timer;

    // code for IE7+, Firefox, Chrome, Opera, Safari
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // 2.设置请求方式和请求地址
    /*
    method:请求的类型;GET 或 POST
    url:文件在服务器上的位置
    async:true(异步)或 false(同步)
    */
    if (type === "GET") {
        xmlHttp.open(type, url + "?" + str, true);
        // 3.发送请求
        xmlHttp.send();
    } else {
        xmlHttp.open(type, url, true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.send(str);
    }

    // 4.监听状态的变化
    xmlHttp.onreadystatechange = (event) => {
        /*
        0: 请求未初始化
        1: 服务器连接已建立
        2: 请求已接收
        3: 请求处理中
        4: 请求已完成,且响应已就绪
        */
        if (xmlHttp.readyState === 4) {
            clearInterval(timer);
            // 判断是否请求成功
            if (xmlHttp.status >= 200 && xmlHttp.status < 300 ||
                xmlHttp.status === 304) {
                // 5.处理返回的结果
                // console.log("接收到服务器返回的数据");
                success(xmlHttp);
            } else {
                // console.log("没有接收到服务器返回的数据");
                error(xmlHttp);
            }
        }
    }

    // 判断外界是否传入了超时时间
    if (timeout) {
        timer = setInterval(() => {
            console.log("中断请求");
            xmlHttp.abort();
            clearInterval(timer);
        }, timeout);
    }
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax-post</title>
    <script src="myAjax.js"></script>
    <script>
        window.onload = function () {
            let oBtn = document.querySelector("button");
            oBtn.onclick = function () {
                ajax("POST", "ajax-post.php", {
                    "userName": "BNTang",
                    "userPwd": "123"
                }, 3000, (xhr) => {
                    alert(xhr.responseText)
                }, () => {
                    console.log("请求失败");
                });
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-post.php:

<?php
echo $_POST["userName"];
echo $_POST["userPwd"];
?>
posted @   BNTang  阅读(103)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示