用Promise封装一个ajax

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <script>
        function ajaxData(url, method, data) {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.open(url, method);
                if (method == "post") {
                    xhr.setRequestHeader("Content-Type", "application/json");
                }
                xhr.send(data);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4) {
                        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                            resolve(xhr.response);
                        }
                    } else {
                        reject("请求失败!");
                    }
                };
            });
        }
    </script>
</body>

</html>

 

posted @ 2023-02-13 11:03  芬-mi  阅读(9)  评论(0编辑  收藏  举报