function $(i) {
return document.getElementById(i);
}
function Ajax() {
var _xmlHttp = null;
var _isAsynchronism = true;
var _successFunction = null;
this.createXMLHttpRequest = function () {
try {
if (window.ActiveXObject) {
_xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
if (window.XMLHttpRequest) {
_xmlHttp = new XMLHttpRequest();
} else {
_xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
}
}
catch (e) {
alert(e.name + " : " + e.message);
}
};
this.doPost = function (_url, _parameter) {
try {
_xmlHttp.open("POST", _url, _isAsynchronism);
_xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_xmlHttp.send(_parameter);
}catch (e) {
alert(e.name + " : .... " + e.message);
}
};
this.doGet = function (_url, _parameter) {
try {
var _random = Math.round(Math.random() * 10000);
var _getParameter = (_url + "?random=" + _random + "&" + _parameter);
if (_getParameter.length > 255) {
this.doPost(_url, _parameter);
} else {
_xmlHttp.open("GET", _getParameter,_isAsynchronism);
_xmlHttp.send(null);
}
}catch (e) {
alert(e.name + " : " + e.message);
}
};
this.backFunction = function(){
if(_successFunction==null)return;
if(_isAsynchronism){
if ((_xmlHttp.readyState == 4) && (_xmlHttp.status == 200)) {
_successFunction(_xmlHttp);
return;
}
}else{
//[color=red]不知道为什么,火狐下不支持同步,IE下可以[/color]
}
};
this.ajaxRequest = function (_url, _parameter, _method, _asynchronism, _backFunction) {
this.createXMLHttpRequest();
_isAsynchronism = _asynchronism;
_successFunction = _backFunction;
_xmlHttp.onreadystatechange = this.backFunction;
if (_method.toLowerCase() == "post") {
this.doPost(_url, _parameter);
} else {
this.doGet(_url, _parameter);
}
};
}
这是我自己写的ajax的小形模型,自己感觉还蛮好用的
用法:
var url = "ajax.do";
var parameter = "parameter=parameter";
var method = "post";
var asynchronism = true //是否异步
function callBack(xml){}
new Ajax().ajaxRequest(url,parameter,method,asynchronism ,callBack);
对了,在fireBug下可以看到数据已经返回给客户端,问题是 同步时在火狐下调不到 回调函数 ....
IE 下 ,同步与否都正常
[b]问题补充:[/b]
[color=red][/color]谢谢你了,不过这样改 在ie下会报错的
貌似 _xmlHttp.onreadystatechange 不能与 null做比较
在你的提醒下,我又想了一次,既然_xmlHttp.onreadystatechange = this.backFunction;
执行不了,反正数据都返回了,我就手动执行得了
function $(i) {
return document.getElementById(i);
}
function Ajax() {
var _xmlHttp = null;
var _isAsynchronism = true;
var _successFunction = null;
[color=red]var _isExcute = false;[/color]
this.backFunction = function(){
if(_successFunction==null)return;
if(_isExcute)return;
if ((_xmlHttp.readyState == 4) && (_xmlHttp.status == 200)) {
_successFunction(_xmlHttp);
_isExcute = true;
return;
}
};
this.ajaxRequest = function (_url, _parameter, _method, _asynchronism, _backFunction) {
this.createXMLHttpRequest();
_isAsynchronism = _asynchronism;
_successFunction = _backFunction;
_xmlHttp.onreadystatechange = this.backFunction;
if (_method.toLowerCase() == "post") {
this.doPost(_url, _parameter);
} else {
this.doGet(_url, _parameter);
}
this.backFunction();
};
}