不如封装一个原生Ajax

封装原生Ajax

我们常常引用jq就是为了使用上面的ajax,方便又实用。但是jq文件一个高达几十kb,还有近几年jq的发展趋势不容乐观,jq中还迟迟没有改进。于是自己造轮子,下面封装了原生JS ajax 。你可以直接复制拿过来用。

function ajax(obj) {
// 对实参处理
obj = obj || {};
// 定义局部变量
var xmlhttp, type, url, async, dataType, data;
// 默认type为GET
type = obj.type || 'GET';
type = trim(type).toUpperCase();
// 接口
url = obj.url
url = trim(url);
// 默认为异步请求
async = obj.async || true;
// 设置跨域
dataType = obj.dataType || 'HTML';
dataType = trim(dataType).toUpperCase();
// 发送参数
data = obj.data || {};
// 删除左右空格
function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
};
// 定义格式化参数函数
var formatParams = function () {
if (typeof (data) == "object") {
var str = "";
for (var pro in data) {
str += pro + "=" + data[pro] + "&";
}
data = str.substr(0, str.length - 1);
}
if (type == 'GET' || dataType == 'JSONP') {
if (url.lastIndexOf('?') == -1) {
url += '?' + data;
} else {
url += '&' + data;
}
}
}
// 第一步,创建xmlhttprequest对象用来和服务器交换数据。
if (window.XMLHttpRequest) {
//Chrome || Firefox
xmlhttp = new XMLHttpRequest();
} else {
//IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 跨域请求
if (dataType == 'JSONP') {
if (typeof (obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
var callbackName = ('jsonp_' + Math.random()).replace(".", "");
var oHead = document.getElementsByTagName('head')[0];
data.callback = callbackName;
var ele = document.createElement('script');
ele.type = "text/javascript";
ele.onerror = function () {
console.log('failed');
obj.error && obj.error("failed");
};
oHead.appendChild(ele);
window[callbackName] = function (json) {
oHead.removeChild(ele);
window[callbackName] = null;
obj.success && obj.success(json);
};
formatParams();
ele.src = url;
return;
} else {
formatParams();

。。。。。。。。。。。。。

作者:Vam的金豆之路

篇幅有限更多请见扩展链接:http://www.mark-to-win.com/tutorial/50950.html

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章