Posted on 2008-11-09 18:35
G_G 阅读(1811)
评论(0) 编辑 收藏 所属分类:
javascript
不要为 拼写 ajax url 而郁闷了。希望能对大家有帮助。
/*
1.form ajax 使用:
eG: form就是普通的 html form
<input type="button" value="xx" onclick="formAjax('data.jsp',this.form,ajaxReturn)"/>
function ajaxReturn(data){
document.getElementById("div1").innerHTML = data ;
}
2.ajax 使用 :
AjaxFunction
AjaxFunction('url?param=tt¶m2=te',function(text){
alert(text);
});
3.迭代器:
recursiveNodes(array,dom,pushFun,layer)
array 迭代寄存器
dom 被迭代对象
pushFun 自定义收集方法
pushFun(array,node,layer)
node 迭代中对象
layer 深度
EG:
var arr = [] ;
recursiveNodes(arr ,dom,function(array,node,layer){
arr.push(node);
},2);
*/
var _request;
try {
this._request = new XMLHttpRequest();
} catch (e) {
try {
this._request = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
this._request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
request = false;
}
}
}
var AjaxFunction = function(urls, getAjaxText) {
AjaxFunction._getAjaxText = null;
_url = '';
_params = '';
AjaxFunction._getAjaxText = getAjaxText;
var strs = urls.split(/\?/);
_url = strs[0];
if (strs.length > 1)
_params = strs[1];
_request.open("POST", this._url, true);
_request.setRequestHeader("Cache-Control", "no-cache");
_request.setRequestHeader("content-type",
"application/x-www-form-urlencoded");
_request.send(_params);
_request.onreadystatechange = _onComplete;
};
function _onComplete() {
if (_request.readyState == 4) {
if (_request.status == 200 || _request.status == 0) {
if (_request.responseText != null && _request.responseText != ''
&& _request.responseText != ' ')
AjaxFunction._getAjaxText(_request.responseText);
}
}
}
/*
* 迭代 1. array,dom 2. array,dom,layer
*/
function recursiveNodes(array, dom, pushFun, layer) {
if (layer == 0)
return;
if (layer > 0) {
--layer;
if (dom.hasChildNodes && dom.hasChildNodes()) {
for ( var i = 0; i < dom.childNodes.length; i++) {
var nodeT = dom.childNodes.item(i);
if (typeof pushFun == "function")
pushFun(array,nodeT, layer);
else
array.push(nodeT);
recursiveNodes(array, dom.childNodes.item(i), pushFun, layer);
}
} else
return;
} else if (layer < 0) {
++layer;
var nodeT = dom.parentNode;
if (nodeT) {
if (typeof pushFun == "function") {
pushFun(array,nodeT, layer);
} else {
array.push(nodeT);
}
recursiveNodes(array, dom.parentNode, pushFun, layer)
} else
return;
}
}
function formAjax(url,ttform,returnFun){
var datas = [];
var arr = ['input','select'];
recursiveNodes(datas,ttform,function(array,node,layer){
for(var i=0;i<arr.length;i++){
if( node.getAttribute ){
var paramName = node.getAttribute('name') ;
if( /select/i.test( node.nodeName ) ){
array.push(paramName+'='+node.options[node.selectedIndex].value);
}else if( paramName !=null && /^\s*(\w+)\s*$/g.test(paramName) && new RegExp(arr[i],'i').test(node.nodeName) ){
array.push(paramName+'='+node.value);
}
}
}
},999);
//? ?
//& &
var urls = url+'?'+datas.join("&");
AjaxFunction(urls,returnFun);
}