原生JavaScript封装Ajax

本文详细介绍了Ajax的基本原理及其实现步骤,包括创建Ajax对象、连接服务器、发送请求和接收返回数据等核心过程,并提供了一个简单的封装函数示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


更多原创博文欢迎本人独立技术博客:蓝克比尔


Ajax的实现主要分为四部分:

1、创建Ajax对象

var xhr=null;
if(window.XMLHttpRequest){
    xhr=newXMLHttpRequest();
}else{
    //为了兼容IE6
    xhr=newActiveXObject('Microsoft.XMLHTTP');
}

 

2、连接服务器

// 连接服务器open(方法GET/POST,请求地址, 异步传输)
xhr.open('GET',  'data.txt',  true);

3、发送请求

// 发送请求
xhr.send();

4、接收返回数据

// 处理返回数据
/*
** 每当readyState改变时,就会触发onreadystatechange事件
** readyState属性存储有XMLHttpRequest的状态信息
** 0 :请求未初始化
** 1 :服务器连接已建立
** 2 :请求已接受
** 3 : 请求处理中
** 4 :请求已完成,且相应就绪
*/
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        /*
        ** Http状态码
        ** 1xx :信息展示
        ** 2xx :成功
        ** 3xx :重定向
        ** 4xx : 客户端错误
        ** 5xx :服务器端错误
        */
        if(xhr.status==200){
            success(xhr.responseText);
        }else{
            if(failed){
                failed(xhr.status);
            }
        }
    }
}


Ajax封装函数:

functionAjax(type,url,data,success,failed){
    // 创建ajax对象
    varxhr=null;
    if(window.XMLHttpRequest){
        xhr=newXMLHttpRequest();
    }else{
        xhr=newActiveXObject('Microsoft.XMLHTTP')
    }
 
    vartype=type.toUpperCase();
    // 用于清除缓存
    varrandom=Math.random();
 
    if(typeofdata=='object'){
        varstr='';
        for(varkeyindata){
            str+=key+'='+data[key]+'&';
        }
        data=str.replace(/&$/,'');
    }
 
    if(type=='GET'){
        if(data){
            xhr.open('GET',url+'?'+data,true);
        }else{
            xhr.open('GET',url+'?t='+random,true);
        }
        xhr.send();
 
    }elseif(type=='POST'){
        xhr.open('POST',url,true);
        // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(data);
    }
 
    // 处理返回数据
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                success(xhr.responseText);
            }else{
                if(failed){
                    failed(xhr.status);
                }
            }
        }
    }
}
 
// 测试调用
varsendData={name:'asher',sex:'male'};
Ajax('get','data/data.html',sendData,function(data){
    console.log(data);
},function(error){
    console.log(error);
});

更多原创博文欢迎本人独立技术博客:蓝克比尔
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值