您的位置:首页 > 其它

自用的简单封装ajax,试用初学者

2017-03-22 15:39 239 查看
(function (window) {
//避免污染全局变量
function ajax(options) {
var init = {
type: 'get',
url: "",
data: {},
async: true,
success: function (txt) {
},
error: function () {
},
cache: true,
beforeSend: function () {
},
complete: function () {
}
};
options = merge(init, options);
options.data = hb(options.data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
//用一个变量来保存是否是post提交方式  值为布尔值
var is_post = /^post$/i.test(options.type);
//来判断是否需要处理url get方式的data需要加到url中
if (!is_post) {
//没有考虑到url可能已经有参数
//优先级的问题 &的问题
options.url += (options.url.indexOf('?') > -1 ? "&" : '?') + options.data;
//处理缓存 是否加上时间戳
options.url += options.cache ? "" : '&__time__=' + new Date().getTime();
}
xhr.open(options.type, options.url, options.async);
//开始动画
options.beforeSend();
//设置头文件
if (is_post) {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {

if (xhr.status == 200) {
//提供xhr的使用权限  方便在使用时可以获取xhr的其他属性
options.success(xhr.responseText, xhr);
//                    complete();
} else {
options.error(xhr.status, xhr);
}
options.complete();
}
}

}
function merge(init, add) {
for (var key in add) {
if (key in init) {
init[key] = add[key];
}
}
return init;
}
function hb(obj) {
var str = "";
for(var key in obj){
str+= key+'='+obj[key]+'&';
}
return str;
}
window.ajax=ajax;
})(window);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: