javascript原生ajax请求

class Ajax{

        constructor(url, method, data, callback_suc, callback_err, callback_run){
            this.RT = true;//默认为异步请求
            this.url = url;
            this.method = method || "POST";
            this.data = data || "";
            this.callback_suc = callback_suc || function () {};
            this.callback_err = callback_err || function () {};
            this.callback_run = callback_run || function () {};
            if(!this.url){this.callback_err(); return;}
            this.createRequest();
        }

        createRequest(){
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = (e)=>{this.run(e);}
            xhr.open(this.method, this.url, this.RT);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(this.data);
        }

        run(e){
            this.callback_run(e);
            if(e.target.readyState !== 4 || e.target.status !== 200){return;}
            this.callback_suc(e);
        }

    }

    new Ajax(//调用
        "./main.php", //url:请求地址
        "POST", //method:请求方法
        "data=3&sb=2",//data:传递数据
        (e)=>{//callback_suc:请求完成 回调函数
            document.write(e.target.responseText);//3
        }
        (e)=>{}//callback_err:请求错误 回调函数
        (e)=>{}//callback_run:请求中 回调函数
    )

上面是js代码

下面以main.php为例接收请求

<?php
    //接收客户端请求数据data和sb
    $data = isset($_GET[‘data‘]) ? $_GET[‘data‘] : "data为空";
    $sb = isset($_GET[‘sb‘]) ? $_GET[‘sb‘] : "sb为空";
    //向客户端返回数据
    echo $data." ".$sb;
?>

相关推荐