
正文
兼容IE, Chrome的ajax function
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
gAjax.js
var gAjax = (function () {
/*
paramObj:{
url: request url,
method: GET or POST,
encode: character,
param: post param,
isAsync: boolean,
returnType: xml/text,
onAjaxComplete: function
}
*/
var _send_ajax = function (paramObj) {
var url, method, encode, httpRequest, param, isAsync, parser, returnType;
var onAjaxComplete;
url = paramObj.url;
method = paramObj.method.toUpperCase();
encode = paramObj.encode;
if (method == 'GET')
param = null;
else if (method == 'POST')
param = paramObj.param;
isAsync = paramObj.isAsync;
returnType = paramObj.returnType || "xml";
onAjaxComplete = paramObj.onAjaxComplete;
if (window.ActiveXObject) {//IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else {//FireFox,Chrome,Safari
httpRequest = new XMLHttpRequest();
}
httpRequest.onreadystatechange = function () {
) {
) {
if (returnType.toUpperCase() == "XML") {
if (window.ActiveXObject) {//IE
parser = new ActiveXObject("Microsoft.XMLDOM");
parser.async = false;
parser.load(httpRequest.responseXML);
} else if (document.implementation.createDocument) {
try {//FireFox
parser = document.implementation.createDocument("", "", null);
parser.async = false;
parser = (new DOMParser()).parseFromString(httpRequest.responseText, "text/xml");
} catch (e) {//Chrome,Safari
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", httpRequest.responseText, false);
xmlhttp.send(null);
parser = xmlhttp.responseXML.documentElement;
}
}
} else {
parser = httpRequest.responseText;
}
onAjaxComplete.apply(_send_ajax, [parser]);
} else {
alert("远程服务调用失败!");
}
}
}
httpRequest.open(method, url, isAsync);
if (typeof encode != 'undefined')
if (method == 'GET')
httpRequest.setRequestHeader("Content-Type", "text/html;charset=" + encode);
else if (method == 'POST')
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + encode);
httpRequest.send(param);
}
return {
sendAjax: _send_ajax
}
})();
用法:
<script>
function loadAjax() {
gAjax.sendAjax({
url:"Server.aspx",
method:'POST',
encode:'GBK',
param:" + "&time=" + new Date(),
isAsync: true,
returnType: 'TEXT',
onAjaxComplete:function(data){
alert(data);
}
});
}
</script>






