原生Javascript封装的一个AJAX函数分享
最近的工作中涉及到大量的ajax操作,本来该后台做的事也要我来做了.而现在使用的ajax函数是一个后台人员封装的—-但他又是基于jquery的ajax,所以离开了jquery这个函数就毫无作用了.而且我觉得,jquery的ajax方法是很完善的了,可以直接用,如果都有jquery了,那么他的ajax就不用白不用了.我缺少的是一个能在没有jquery的情况下使用的ajax方法.
所以我也花一天时间写了一个,参数与调用方法类似于jquery的ajax.就叫xhr吧,因为xhr=XMLHttpRequest.
/*
* Name: xhr,AJAX封装函数
* Description: 一个ajax调用封装类,仿jquery的ajax调用方式
* Author:十年灯
*/
var xhr = function () {
var
ajax = function () {
return ('XMLHttpRequest' in window) ? function () {
return new XMLHttpRequest();
} : function () {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}(),
formatData= function (fd) {
var res = '';
for(var f in fd) {
res += f+'='+fd[f]+'&';
}
return res.slice(0,-1);
},
AJAX = function(ops) {
var
root = this,
req = ajax();
root.url = ops.url;
root.type = ops.type || 'responseText';
root.method = ops.method || 'GET';
root.async = ops.async || true;
root.data = ops.data || {};
root.complete = ops.complete || function () {};
root.success = ops.success || function(){};
root.error = ops.error || function (s) { alert(root.url+'->status:'+s+'error!')};
root.abort = req.abort;
root.setData = function (data) {
for(var d in data) {
root.data[d] = data[d];
}
}
root.send = function () {
var datastring = formatData(root.data),
sendstring,get = false,
async = root.async,
complete = root.complete,
method = root.method,
type=root.type;
if(method === 'GET') {
root.url+='?'+datastring;
get = true;
}
req.open(method,root.url,async);
if(!get) {
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
sendstring = datastring;
}