ajax封装

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封装ajax</title>
</head>
<body>
<script>
    function ajax_fz(method,url,params,Done) {
        var xhr= new XMLHttpRequest();
        //把method转化为大写字母
        method.toUpperCase();
        //如果params typeof===object 转成字符串
        if (typeof params==='object'){
            tempArr=[];
            //遍历数组的每一个键
            for (var key in params){
                var value=params[key];
                //把每个元素的键值用  =  拼接起来
                tempArr.push(key+'='+value);
            }
            //tempArr每个元素之间用  &  拼接起来
            params=tempArr.join('&');
        }
        //当请求方式是GET时
        if (method==='GET'){
            url+='?'+params;
        }
        //设置请求方式,请求地址
        xhr.open(method,url);
        data=null;
        //当请求方式是POST时
        if (method==='POST'){
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            data=params;
        }
        //设置发送请求体
        xhr.send(data);
        xhr.onreadystatechange=function(){
            if (this.readyState==4){
                Done(this.responseText);
            }
        }
    }
    //回调
    var onDone = function(res){
        console.log('hahahhahah');
        console.log('huohuohuo');
        console.log(res);
        console.log('成功了');
    }

    ajax_fz('GET','/text.php', {id:'1'},onDone);
</script>
</body>
</html>

你可能感兴趣的:(笔记)