码迷,mamicode.com
首页 > Web开发 > 详细

封装ajax

时间:2016-06-12 13:43:14      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

  var sendData = function(options) {
        var mat = options.url.match(/https?:\/\/([^\/]+)/);
        if (mat && location.host != mat[0]) {
            jsonp(options);
        } else {
            ajax(options);
        }
    }

    var jsonp = function(options) {
        options = options || {};
        if (!options.url) {
            throw new Error("Parameter is not valid");
        }
        var callbackName = (jsonp_ + Math.random()).replace(".", "");
        var oHead = document.getElementsByTagName(head)[0];       
        var oS = document.createElement(script);
        oHead.appendChild(oS);
        window[callbackName] = function(json) {
            oHead.removeChild(oS);
            clearTimeout(oS.timer);
            window[callbackName] = null;
            options.success && options.success(json);
        };
        if (options.url.indexOf(?) == -1) {
            oS.src = options.url + ?callback= + callbackName;
        } else {
            oS.src = options.url + &callback= + callbackName;
        }
        if (options.time) {
            oS.timer = setTimeout(function() {
                window[callbackName] = null;
                oHead.removeChild(oS);
                options.fail && options.fail({
                    message: "timeOut"
                });
            }, time);
        }
    }
    var ajax = function(options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        var params = formatParams(options.data);
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else {
            var xhr = new ActiveXObject(Microsoft.XMLHTTP);
        }
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        }
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, true);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", options.url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(params);
        }
    }

 

封装ajax

标签:

原文地址:http://www.cnblogs.com/xiaotaiyang/p/5577133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!