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);
}
}