原生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 @   何效名  阅读(127)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-08-04 JS 模拟表单提交,实现POST方式跳转
点击右上角即可分享
微信分享提示