原生js实现Ajax

Ajax:页面无刷新请求数据

原生js实现ajax(简单封装)

var ajax = {
    //创建xmlHttpRequest对象
    createXmlHttpRequest: function(){
        var xhr = null;
        try{
            xhr = new XMLHttpRequest();//firefox Opera 8.0+, Safari
        }catch(e){
            try{
                xhr = new ActiveXObject("Msxml2.XMLHTTP");//IE 6.0+
            }catch(e){
                xhr = new ActiveXObject("Microsoft.XMLHTTP");//IE 5.5+
            }
        }
        return xhr;
    },
    /*
     *  method    -> 请求方式 post/get
     *  url       -> 请求的资源路径url
     *  dataPost  -> get 如 ?name='ys'&age=12;
     *               post如 {'data':12,'age':12};
     *  callback  ->回调函数
     **/
    judgeXmlHttpRequest: function(method, url, callback, dataPost){
        var xhr = this.createXmlHttpRequest();//先创建
        if(xhr){
            var resData = undefined;
            //true表示异步请求
            xhr.open(method, url ,true);
            if(method === 'post'){
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xhr.send(dataPost);
            }else{
                xhr.send(null);
            }
            //readyState表示请求/响应过程的状态0-4
            //readyState每次变化,都会触发readystatechange事件
            xhr.onreadystatechange = function(){
                //
                if(xhr.readyState === 4 && xhr.status === 200){
                    //resData = xhr.responseXML; 响应XML数据
                    //响应文本数据
                    resData = xhr.responseText;
                    //回调函数
                    callback(resData);
                }
            }
        }   
    }
}

说明:ajax.judgeXmlHttpRequest()方法有4个形参,get方法只用了3个,不是语法错误,JavaScript引擎将会忽略第四个形参

调用代码

get方法

    ajax.judgeXmlHttpRequest('get', 'index.php', function(data){
        alert(data);    //这是服务器返回的数据
    })     

post方法

    var dataJson = {
        name: 'ys',
        age: 123 
    }
    ajax.judgeXmlHttpRequest('post', 'index.php', function(data){
        alert(data);    //这是服务器返回的数据
    },dataJson)  

说明:
在form元素中,enctype表明提交数据的编码格式

  • content-type:application/x-www-form-urlencoded,(标准编码)窗体数据被编码为名称/值对(和post封装的json一样);
  • content-type:multipart/form-data, 窗体数据被编码为一条消息,不对字符编码。(上传文件必须该编码方式)
  • content-type:text/plain: 窗体数据以纯文本形式进行编码

而这里的post请求采用了默认的application/x-www-form-urlencoded进行编码,编码+消息体,使得post更安全

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值