How to write and use Ajax classes
This article introduces the relevant knowledge of "how to write and use Ajax classes". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Program code:
Function Ajax (sUrl,sRecvTyp,sQueryString,oResultFunc) {
This.Url = sUrl
This.QueryString = sQueryString
This.XmlHttp = this.createXMLHttpRequest ()
If (this.XmlHttp = = null) {
Alert ("erro")
Return
}
Var objxml = this.XmlHttp
Objxml.onreadystatechange = function () {Ajax.handleStateChange (objxml,sRecvTyp,oResultFunc)}
}
Ajax.prototype.createXMLHttpRequest = function () {
Try {return new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {}
Try {return new ActiveXObject ("Microsoft.XMLHTTP");} catch (e) {}
Try {return new XMLHttpRequest ();} catch (e) {}
Return null
}
Ajax.prototype.createQueryString = function () {
Var queryString = this.QueryString
Return queryString
}
Ajax.prototype.get = function () {
SUrl = this.Url
Var queryString = sUrl+ "? timeStamp=" + new Date (). GetTime () + "&" + this.createQueryString ()
This.XmlHttp.open ("GET", queryString,true)
This.XmlHttp.send (null)
}
Ajax.prototype.post = function () {
SUrl = this.Url
Var sUrl = sUrl + "timeStamp=" + new Date () .getTime ()
Var queryString = this.createQueryString ()
This.XmlHttp.open ("POST", sUrl,true)
This.XmlHttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")
This.XmlHttp.send (queryString)
}
Ajax.handleStateChange = function (XmlHttp,sRecvTyp,oResultFunc) {
If (XmlHttp.readyState = = 4) {
If (XmlHttp.status = = 200) {
OResultFunc (sRecvTyp?XmlHttp.responseXML:XmlHttp.responseText)
} else {
Alert ("there is an exception in the page you requested.")
}
}
}
How to use it:
Var classAjax = new Ajax (sUrl,sRecvTyp,sQueryString,oResultFunc)
Send data in classAjax.post (); / / post mode
Send data in classAjax.get (); / / get mode
/ / sUrl sending address
/ / sRecvTyp accepts data type: 0 is xml 1 is text
/ / oResultFunc returns the result handling function
Application example:
Var ajax1 = new Ajax ("1.asp", 0, "id=" + id,bacal)
Ajax1.post ()
Function bacal (rexm) {
/ / return data processing function
}
That's all for "how to write and use Ajax classes". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!