原生JavaScript 封装ajax方法

 


 封装类:

class Ajax
{
    constructor(obj)
    {
        var async = obj.async == undefined ? true : obj.async;

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            if(xhr.readyState == 4 && xhr.status == 200)
            {
                obj.callback(xhr.responseText);
            }
        }

        if(obj.method == "get")
        {
            xhr.open(obj.method, obj.url, async);
            xhr.send(null);
        }
        else if(obj.method == "post")
        {
            xhr.open(obj.method, obj.url, async);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            obj.data = (function(value)
            {
                let tmp = '';
                for(var key in value)
                {
                    tmp += key + '=' + value[key] + '&';
                }
                return tmp.substring(0, tmp.length - 1);
            }(obj.data));

            xhr.send(obj.data);
        }
        else
        {
            console.log("method可选值为'get'及'post'");
            return false
        }
    }
}

 

调用:

new Ajax(
{
    url: 'http://127.0.0.1/',
    method: 'post',
    async: false,
    data: {'abc': 1, 'a49s': 2},
    callback: function(res)
    {
        console.log(res);
    }
});

 

posted @ 2022-08-04 16:53  何效名  阅读(125)  评论(0编辑  收藏  举报