Ajax封装及解释(解决IE兼容、传参数、超时、url中有中文 的问题)

自封装的Ajax.js文件

//定义一个obj2str方法,将传入的obj参数对象转为字符串
function obj2str(data) {
    data.t=new Date().getTime();
    var res=[];
    for(var key in data){
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));//防止传入中文
    }
      return res.join("&");
}
function ajax(option) {
    //0、将对象转为字符串
    var str=obj2str(option.data);
    //1、创建一个异步对象
    var xmlhttp,timer;
    if(window.XMLHttpRequest){
        //兼容IE7+,Firefox,Chrome,Opera,Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        //兼容IE6、IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
/*    //2、设置请求方式和请求地址
    xmlhttp.open("GET", url+"?"+str, true);

    //POST请求使用setRequestHeader()来添加HTTP头,必须放在open和send之间
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    //3、发送请求
    xmlhttp.send();*/

    //上面的注释可改为如下:
    if(option.type==="GET"){
        //get请求
        xmlhttp.open(option.type,option.url+"?"+str,true);
        xmlhttp.send();
    }else{
        //post请求
        xmlhttp.open(option.type,option.url,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);
    }
    //4、监听异步对象状态的变化
    xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState === 4) {
            clearInterval(timer);
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
                //5、处理返回的结果

                //成功时传出异步对象执行回调函数
                option.success(xmlhttp);
            } else {
               option.error(xmlhttp);
            }
        }
    }
    //判断外界是否传入了超时时间
    if(option.timeout){
        timer=setInterval(function () {
                console.log("中断请求");
                xmlhttp.abort();  //调用异步对象的abort()方法中断请求
                clearInterval(option.timer); //停止定时器
        },option.timeout);
    }
}

调用Ajax方法的index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="111.js"></script>
    <script>
        window.onload=function () {
            var oBtn=document.querySelector("button");
            oBtn.onclick=function () {
                ajax({ type:"POST/GET",//参数1:请求类型
                       url:"https://www.baidu.com或php等后端文件",//参数2:请求地址
                       data:{"userName":"你的名字","password":"你的密码"},//参数3:要传入的参数
                       timeout: 3000,//参数4:超时时间
                       sunccess:function (xhr) {
                    alert(xhr.responseText);
                },//参数5:成功时的回调函数
                       error: function (xhr) {
                    alert("请求失败");//参数6:失败时的回调函数
                })
            }
			}
        }
    </script>
</head>
<body>
<button> 发送请求</button>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值