首页 > Web开发 > 详细

Ajax原生写法

时间:2016-02-19 12:30:02      阅读:201      评论:0      收藏:0      [点我收藏+]

用太久JQuery了,别忘了Ajax原生是怎么写的

技术分享
var Ajax = {
    get : function (url, callback) {
        
        var req = Ajax.getRequest(callback);
        
        req.open("GET", url, true);
        req.setRequestHeader("If-Modified-Since","0");
        req.send(null);
    },
    post : function (url, param, callback) {
        
        var req = Ajax.getRequest(callback);
        
        req.open("POST", url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        req.setRequestHeader("If-Modified-Since","0");
        req.send(param);
    },
    getRequest : function (callback) {
        var req;
        try {
            req = new XMLHttpRequest();
        } catch (error) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (error) {
                return null;
            }
        }
        req.onreadystatechange = function() {
            if (req.readyState != 4)
                return;
            if (req.status == 200) {
                callback(req);
            } else
                alert("请求失败:" + req.statusText);
            return true;
        };
        return req;
    },
    encode : function (str) {
        return encodeURIComponent(str);
    }
};

 

 

Ajax原生写法

原文:http://www.cnblogs.com/libaoli/p/5200506.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!