欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

自己动手封装的 ajax

程序员文章站 2022-03-14 10:41:03
以前开发用了很多ajax的技术比如ext,prototype,jquery等等,但都是开源封装好的ajax框架。从没真正用过纯正的ajax,故参照prototyp面向对象思...
以前开发用了很多ajax的技术比如ext,prototype,jquery等等,但都是开源封装好的ajax框架。从没真正用过纯正的ajax,故参照prototyp面向对象思想自己封装了一个ajax框架。希望能给读者参考、帮助、评价。
复制代码 代码如下:

/*
* 自己封装的ajax
*
*
* @author 姜松
* @version 1.00 $date:2009-07-02
*
* history:
*
*/
object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
object.extend(string.prototype, {
include: function(pattern) {
return this.indexof(pattern) > -1;
},
startswith: function(pattern) {
return this.indexof(pattern) == 0;
},
endswith: function(pattern) {
return this.lastindexof(pattern) == (this.length - pattern.length);
},
empty: function() {
return /^\s*$/.test(this) || this == undefined || this == null;
}
});
object.extend(array.prototype, {
each: function(iterator) {
try {
for (var i = 0, length = this.length; i < length; i++) {
iterator(this[i]);
}
} catch (e) {
if (e != 'break') { throw e };
}
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
indexof: function(object) {
for (var i = 0, length = this.length; i < length; i++) {
if (this[i] == object) {return i};
}
return -1;
},
size: function() {
return this.length;
},
include: function(object) {
var found = false;
this.each(function(value) {
if (value == object) {found = true; throw 'break';}
});
return found;
}
});
function $(element) {
if(arguments.length > 1) {
for(var i = 0, elements = [], length = arguments.length; i < length; i++) {
elements.push($(arguments[i]));
}
return elements;
}
if(typeof element == 'string') {
element = document.getelementbyid(element);
}
return element;
};
var ajax = {
transport: new object(),
options: new object(),
gettransport: function() {
if(window.activexobject) {
try {
return new activexobject('msxm12.xmlhttp');
} catch(e) {
try {
return new activexobject('microsoft.xmlhttp');
} catch(e) {}
}
} else if(window.xmlhttprequest) {
try {
return new xmlhttprequest();
} catch(e) {}
}
},
setoptions: function(options) {
ajax.options = {
method: 'get',
asynchronous: true,
contenttype: 'application/x-www-form-urlencoded',
encoding: 'utf-8',
parameters: ''
};
object.extend(ajax.options, options);
ajax.options.method = ajax.options.method.touppercase();
},
request: function(url, options) {
ajax.transport = ajax.gettransport();
ajax.setoptions(options);
this.method = ajax.options.method;
var params = ajax.options.parameters;
if (!['get', 'post'].include(this.method)) {
this.method = 'get';
}
if (this.method == 'get') {
url = ajax.setparameters(url, params);
}
try {
ajax.transport.open(this.method, url, ajax.options.asynchronous);
ajax.transport.onreadystatechange = ajax.statechange;
ajax.setrequestheaders();
this.body = this.method == 'post' ? params : null;
ajax.transport.send(this.body);
} catch (e) {}
},
statechange: function() {
try {
var readystate = ajax.transport.readystate;
if(readystate == 4) {
var status = ajax.transport.status, transport = ajax, json = ajax.evaljson();
if(status == 200) {
ajax.options['onsuccess'](transport, json);
} else {
ajax.options['onfailure'](transport, json);
}
}
} catch (e) {}
},
setparameters: function(url, params) {
if (params && typeof params == 'string') {
url += (url.include('?') ? '&' : '?') + params;
} else if (params && typeof params == 'object') {
for(var param in params) {
url += (url.include('?') ? '&' : '?') + param + '=' + params[param];
}
}
return url;
},
setrequestheaders: function() {
var headers = {
'x-requested-with': 'xmlhttprequest',
'accept': 'application/xml, text/xml, text/html, text/javascript, application/javascript, application/json, text/javascript, text/plain, */*',
'if-modified-since': 'thu, 01 jan 1970 00:00:00 gmt'
};
this.method = ajax.options.method;
if (this.method == 'post') {
headers['content-type'] = ajax.options.contenttype +
(ajax.options.encoding ? '; charset=' + ajax.options.encoding : '');
if (ajax.transport.overridemimetype &&
(navigator.useragent.match(/gecko\/(\d{4})/) || [0,2005])[1] < 2005) {
headers['connection'] = 'close';
}
}
for (var name in headers) {
ajax.transport.setrequestheader(name, headers[name]);
}
},
evaljson: function() {
try {
return eval('(' + ajax.transport.responsetext + ')');
} catch (e) {}
}
};
var form = {
serialize: function(element) {
var elements = $(element).all;
var querycomponents = [];
for(var i = 0; i < elements.length; i++) {
var parameter = null, method = elements[i].tagname.tolowercase();
if(['input', 'select', 'textarea'].include(method)) {
parameter = form.serializers[method](elements[i]);
}
if(parameter != null && parameter.constructor == array) {
var key = encodeuricomponent(parameter[0]);
var value = encodeuricomponent(parameter[1]);
querycomponents.push(key + '=' + value);
}
}
return querycomponents.join('&');
},
request: function(options) {
var params = this.toqueryparams(options.parameters);
options.parameters = this.serialize(this.form);
if(params) {
options.parameters = options.parameters.concat('&' + params);
}
if($(this.form).method) {
options.method = $(this.form).method;
}
return new ajax.request($(this.form).action, options);
},
toqueryparams: function(params) {
var querycomponents = [];
if (params && typeof params == 'string') {
querycomponents.push(encodeuricomponent(params));
} else if (params && typeof params == 'object') {
for(var param in params) {
var key = encodeuricomponent(param);
var value = encodeuricomponent(params[param]);
querycomponents.push(key + '=' + value);
}
}
return querycomponents.join('&');
}
};
form.serializers = {
input: function(element) {
switch(element.type.tolowercase()) {
case 'checkbox':
case 'radio':
return this.inputselector(element);
default:
return this.textarea(element);
}
},
inputselector: function(element) {
if(element.checked) {
return [element.name, element.value];
}
},
textarea: function(element) {
return [element.name, element.value];
},
select: function(element) {
return this[element.type == 'select-one' ?
'selectone' : 'selectmany'](element);
},
selectone: function(element) {
var value = null, option, index = element.selectedindex;
if(index >= 0) {
option = element.options[index];
value = option.value == (undefined || '') ? option.text : option.value;
}
return [element.name, value];
},
selectmany: function(element) {
var value = [];
for(var i = 0; i < element.length; i++) {
var option = element.options[i];
if(option.selected) {
var optvalue = option.value == (undefined || '') ? option.text : option.value;
value.push(optvalue);
}
}
return [element.name, value];
}
};
function $f(element) {
this.form = element;
}
object.extend($f.prototype, form);
/**************************************************************
* 测试函数
*/
function ontest() {
//get提交方法
var params = new object();
params.ss = '张三';
new ajax.request('ajax.do?method=doget', {
onsuccess: function(transport) {
alert(transport.evaljson().xx)
},
parameters: params
});
//post form提交方法
var params = new object();
params.idd = 1000;
params.names = '张三'
new $f('form').request({
onsuccess: function(transport) {
alert(transport.evaljson().xx);
},
parameters: params
});
}