用原生js写出类似于ajax请求程序

14 篇文章 0 订阅
2 篇文章 0 订阅

myajax是一个用js编写的一个跨浏览器的ajax库,支持get, post, jsonp请求,精巧,简单。

源码:

var myajax = {
 
    post: function(params){
        var xmlhttp = this.createXMLHttpRequest();
        if (xmlhttp != null)
        {
            var async = true;
            if (typeof params.async != "undefined")
                async = params.async;
            var data = null;
            if (typeof params.data != "undefined")
                data = params.data;
            var url = "";
            if (typeof params.url != "undefined")
                url = params.url;
            if (url == null || url.length == 0)
                return;
            xmlhttp.open("POST", url, async);//第三个参数决定同步异步方式请求,如果是同步,后续send()方法将阻塞。
            if (async){
                xmlhttp.onreadystatechange = function(){
                 
                    if (this.readyState==4){
                        if (this.status==200){
 
                            if (typeof params.success != "undefined") {
                                params.success(xmlhttp.responseText);
                            }
                        }
                        else {
                            if (typeof params.error != "undefined") {
                                params.error(xmlhttp.status + xmlhttp.statusText);
                            }
                            console.error(url + ": " + xmlhttp.status);
                        }
                    }
                };
            }
             
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var param = "";
            for (var prop in data) {
                param += prop + "=" + data[prop] + "&";
            }
            param = param.substring(0, param.length - 1);
            xmlhttp.send(param);
            if (!async) {
                 
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
         
                    if (typeof params.success != "undefined") {
                        params.success(xmlhttp.responseText);
                    }
                else {
                    if (typeof params.error != "undefined") {
                        params.error(xmlhttp.status + xmlhttp.statusText);
                    }
                    console.error(url + ": " + xmlhttp.status);
                }
                 
            }
        }
    },
    get: function(params){
        var xmlhttp = this.createXMLHttpRequest();
        if (xmlhttp != null)
        {
            var async = true;
            if (params.async != undefined)
                async = params.async;
            var url = "";
            if (params.url != undefined)
                url = params.url;
            if (url == null || url.length == 0)
                return;
            if (params.data != null) {
                var data = params.data;
                var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";
         
                url = url + paramPrefix;
                for (var prop in data) {
                    url += prop + "=" + data[prop] + "&";
                }
                url = url.substring(0, url.length - 1);
            }
            xmlhttp.open("GET", url, async);
            if (async){
                xmlhttp.onreadystatechange = function(){
                    if (this.readyState==4){
                        if (this.status==200){
                            if (typeof params.success != "undefined") {
                                params.success(xmlhttp.responseText);
                            }
                        }
                        else {
                            if (typeof params.error != "undefined") {
                                params.error(xmlhttp.status + xmlhttp.statusText);
                            }
                            console.error(url + ": " + xmlhttp.status);
                        }
                    }
                };
            }
 
            xmlhttp.send(null);
            if (!async) {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    if (typeof params.success != "undefined") {
                        params.success(xmlhttp.responseText);
                    }
                else {
                    if (typeof params.error != "undefined") {
                        params.error(xmlhttp.status + xmlhttp.statusText);
                    }
                    console.error(url + ": " + xmlhttp.status);
                }
                         
                 
            }
        }
    },
    createXMLHttpRequest: function(){
        if (window.XMLHttpRequest)
        {
            return new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
        //code for IE5 and IE6
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        return null;
    },
    getJSONP: function(params) {
 
        var url = null;
        if (typeof params.url != "undefined") {
            url = params.url;
        }
        if (url == null) {
            return;
        }
         
        var ff = "" + new Date().getTime() + (parseInt(Math.random() * 10000000000));
        eval("jsonpCallback_" + ff + "=" + function(data){
     
            if (typeof params.success != "undefined") {
                params.success(data);
            }
        });
 
        //根据url中是否出现过 "?" 来决定添加时间戳参数时使用 "?" 还是 "&" 
        var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";
 
        url = url + paramPrefix + "jsonpCallback=" + "jsonpCallback_" + ff;
        var param = "";
 
        if (typeof params.data != "undefined" && params.data != null) {
         
            var data = params.data;
            for (var prop in data) {
                param += prop + "=" + data[prop] + "&";
            }
            param = param.substring(0, param.length - 1);
        }
        if (param.length > 0)
        url = url + "&" + param; 
        var script = document.createElement("script"); 
        document.body.appendChild(script); 
        script.src = url; 
        script.charset ="UTF-8";
        // for firefox, google etc.
        script.onerror = function() {
            if (typeof params.error != "undefined") {
                params.error();
            }
             
        }
        script.onload = function() {
 
        document.body.removeChild(script); 
        } 
        // for ie 
        script.onreadystatechange = function() { 
          if (this.readyState == "loaded" || this.readyState == "complete") { 
            document.body.removeChild(script);
          } 
        }
    }
 
};


一、发送GET请求:

myajax.get({
data: {}, //参数
    url: "", //请求地址
    //发生错误是调用
    error: function(data) {
    },
    //请求成功调用
    success: function(data){        
//eval(data); 将字符串转换成json
    }
});

二、发送POST请求:

myajax.post({
    data: {}, //参数
    url: "", //
    //发生错误是调用
    error: function(data) {
    },
    //请求成功调用
    success: function(data){
    //eval(data); 将字符串转换成json
    }
});

三、发送JSONP请求

myajax.getJSONP({
//参数
data: {
},
url: "", //请求地址
//请求成功调用
success: function(data) {
},
//发生错误时调用
error: function() {
}
});






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值