【网络】仿JQ之AJAX请求

时间:2021-08-05 16:00:35   收藏:0   阅读:28

总体思路

整体代码

var $ = (function(){
    function doAjax(opt){
        var url = opt.url,
            type = opt.type,
            data = opt.data,
            async = opt.async || true,  //异步模式默认开启
            success = opt.success,
            error = function(){
                throw new Error(‘success must be function‘);
            },
            xhr;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject(‘Mirosoft.XMLHTTP‘);
        }

        xhr.open(type,url,async); //发送HTTP请求
        if(type === ‘POST‘){
            xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘); //POST请求必须设置请求头
            xhr.send(formatData(data));  //发送POST请求
        }else{
            xhr.send(); //GET send的参数为空
        }

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                if(typeof success === ‘function‘){
                    success(JSON.parse(xhr.responseText));
                }else{
                    error();
                }   
            }
        }
    }

    function formatData(data){
        var list = ‘‘;
        for(var name in data){
            list += name + ‘=‘ + data[name] + ‘&‘;
        }
        list.replace(/&$/, ‘‘);  //去除字符串最后的一位&
        return list;
    }
    return {
        ajax: function(opt){
            doAjax(opt);
        },
        get: function(url,callback){
            doAjax({
                url: url,
                type: ‘GET‘,
                success: callback
            });
        },
        post: function(url,data,callback){
            doAjax({
                url: url,
                type: ‘POST‘,
                data: data,
                success: callback
            });
        }
    }
})();

原文:https://www.cnblogs.com/razzh/p/15102609.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!