从松柏那转载的ajax类
常用的一段ajax的代码
下面的代码是我经常使用的一段代码,发上来以备忘
/*-----------------------------ajax关键代码将ajax封装成一个类-----------------------------*/function createAjax() {var xmlHttp = false;
if (window.XMLHttpRequest) { //mozillaxmlHttp = new XMLHttpRequest();//ie6不支持XMLHttpRequest
if (xmlHttp.overrideMimeType) xmlHttp.overrideMimeType("text/xml");
}
else if (window.ActiveXObject) {
var MSXML = ['MSXML2.XMLHTTP.5.0', 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
var i; for(i = 0; i < MSXML.length; i++){ try{ xmlHttp = new ActiveXObject(MSXML[i]); break;}
catch(e){}}
}
if (!xmlHttp) { alert("error! fail to create an ajax instance!"); return false; }
this.rep = xmlHttp;this.sendData = function(method, url, asy, fun) {
if (asy) { xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {fun(xmlHttp);
}
}
if (method == "POST") {
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Conent-Type", "application/x-www-form-urlencoded");
xmlHttp.send(null);}
else {xmlHttp.open("GET", url, true);
xmlHttp.send(null);}
}
else {if (method == "POST") {
xmlHttp.open("POST", url, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(null);}
else {xmlHttp.open("GET", url, false);
xmlHttp.send(null);}
return xmlHttp;}
}
}
使用:
先实例一个对象:
1: var ajax = new createAjax();
再写方法:
1: ajax.sendData("POST", "articleEdit.aspx?RemoveAttachmentID=" + attachmentID + "&NewsID=" + newsID, true, function(xmlhttp) {
2: if (xmlhttp.responseText != "") {
3: 4: //to do something
5: 6: } 7: })
浙公网安备 33010602011771号