xajax.Net
出自ProgWiki
目錄 |
用途
- xajax 的Server端,由php轉移到ASP.NET AJAX。
技術來源
- xajax (以0.2.5版時的code為基礎)
程式碼
檔案:xajaxResponse.cs
- 用途:取代原本的 xajaxResponse.inc.php
xajaxResponse.cs
using System; using System.Data; using System.Text; using System.Collections.Generic; using System.Web; /// <summary> /// xajaxResponse 的摘要描述 /// </summary> public class xajaxResponse { const string XAJAX_DEFAULT_CHAR_ENCODING = "utf-8"; public xajaxResponse() { this.setCharEncoding(XAJAX_DEFAULT_CHAR_ENCODING); this.listCommands = new List< Dictionary<string, string> >(); } public xajaxResponse(string sEncoding) { this.setCharEncoding(sEncoding); this.listCommands = new List<Dictionary<string, string>>(); } // array of internal command storage List<Dictionary<string, string>> listCommands; // string the encoding type to use string strEncoding; // http://tw2.php.net/manual/en/function.explode.php protected List<string> explode(string strSeparator, string strData) { List<string> listSeparator = new List<string>(); listSeparator.Add(strSeparator); List<string> listRet = new List<string>(); listRet.AddRange(strData.Split(listSeparator.ToArray(), StringSplitOptions.RemoveEmptyEntries)); return listRet; } // http://tw2.php.net/manual/en/function.htmlentities.php protected string htmlentities(string strData) { return strData.Replace("<", "<").Replace(">", ">"); } public override string ToString() { //TODO: string ToString() return this.getOutput(); } public void setCharEncoding(string strEncoding) { this.strEncoding = strEncoding.Trim(); } public xajaxResponse addConfirmCommands(int iCmdNumber, string strMessage) { //TODO: addConfirmCommand Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "cc"; cmd["t"] = iCmdNumber.ToString(); cmd["_data"] = strMessage; this.addCommand(cmd); return this; } public xajaxResponse confirmCommands(int iCmdNumber, string sMessage) { return this.addConfirmCommands(iCmdNumber, sMessage); } public xajaxResponse addAssign(string strTarget, string strAttribute, string strData) { //TODO: addAssign Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "as"; cmd["t"] = strTarget; cmd["p"] = strAttribute; cmd["_data"] = strData; this.addCommand( cmd ); return this; } public xajaxResponse assign(string strTarget, string strAttribute, string strData) { return this.addAssign(strTarget, strAttribute, strData); } public xajaxResponse addAppend(string strTarget, string strAttribute, string strData) { //TODO: addAppend Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ap"; cmd["t"] = strTarget; cmd["p"] = strAttribute; cmd["_data"] = strData; this.addCommand( cmd ); return this; } public xajaxResponse append(string strTarget, string strAttribute, string strData) { return this.addAppend(strTarget, strAttribute, strData); } public xajaxResponse addPrepend(string strTarget, string strAttribute, string strData) { //TODO: addPrepend Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "pp"; cmd["t"] = strTarget; cmd["p"] = strAttribute; cmd["_data"] = strData; this.addCommand( cmd ); return this; } public xajaxResponse prepend(string strTarget, string strAttribute, string strData) { return this.addPrepend(strTarget, strAttribute, strData); } public xajaxResponse addReplace(string strTarget, string strAttribute, string strSearch, string strData) { //TODO: addReplace List<Dictionary<string, string>> listData = new List<Dictionary<string, string>>(); { Dictionary<string, string> data1 = new Dictionary<string, string>(); data1["k"] = "s"; data1["v"] = strSearch; listData.Add(data1); Dictionary<string, string> data2 = new Dictionary<string, string>(); data2["k"] = "r"; data2["v"] = strData; listData.Add(data2); } string strDataTotal = this._arrayToXML(listData); Dictionary<string, string> cmd = new Dictionary<string, string>(); cmd["n"] = "rp"; cmd["t"] = strTarget; cmd["p"] = strAttribute; cmd["_data"] = strDataTotal; cmd["_is_array"] = "True"; this.addCommand(cmd); return this; } public xajaxResponse replace(string sTarget, string sAttribute, string sSearch, string strData) { return this.addReplace(sTarget, sAttribute, sSearch, strData); } public xajaxResponse addClear(string strTarget, string strAttribute) { this.assign(strTarget, strAttribute, ""); return this; } public xajaxResponse clear(string strTarget, string strAttribute) { return this.addClear( strTarget, strAttribute); } public xajaxResponse addAlert(string strMsg) { //TODO: addAlert Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "al"; cmd["_data"] = strMsg; this.addCommand( cmd); return this; } public xajaxResponse alert(string strMsg) { return this.addAlert(strMsg); } public xajaxResponse addRedirect(string strUrl, int iDelay) { //TODO: addRedirect string strUrl2 = HttpUtility.UrlEncode(strUrl); if (iDelay != 0) this.addScript(string.Format("window.setTimeout(\"window.location = '{0}';\",{1});", strUrl2, (iDelay*1000))); else this.addScript(string.Format("window.location = \"{0}\";", strUrl2)); return this; } public xajaxResponse addRedirect(string strUrl) { return this.addRedirect( strUrl, 0); } public xajaxResponse redirect(string strUrl, int iDelay) { return this.addRedirect( strUrl, iDelay); } public xajaxResponse redirect(string strUrl) { return this.addRedirect( strUrl, 0); } public xajaxResponse addScript(string strJS) { //TODO: addScript Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "js"; cmd["_data"] = strJS; this.addCommand(cmd); return this; } public xajaxResponse script(string strJS) { return this.addScript(strJS); } public xajaxResponse addScriptCall(params object[] listArgs) { //TODO: addScriptCall if (listArgs.Length >= 1) { string strFunc = listArgs[0] as string; List<Dictionary<string, string>> listData = new List<Dictionary<string, string>>(); for (int i = 1; i < listArgs.Length; i++) { Dictionary<string, string> data1 = new Dictionary<string, string>(); data1["k"] = i.ToString(); data1["v"] = listArgs[i].ToString(); listData.Add(data1); } string strDataTotal = this._arrayToXML(listData); Dictionary<string, string> cmd = new Dictionary<string, string>(); cmd["n"] = "jc"; cmd["t"] = strFunc; cmd["_data"] = strDataTotal; cmd["_is_array"] = "True"; this.addCommand(cmd); } return this; } public xajaxResponse call(params object[] listArgs) { //TODO: call return addScriptCall(listArgs); } public xajaxResponse addRemove(string sTarget) { //TODO: addRemove Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "rm"; cmd["t"] = sTarget; this.addCommand( cmd); return this; } public xajaxResponse remove(string sTarget) { return this.addRemove(sTarget); } public xajaxResponse addCreate(string strParent, string strTag, string strId) { //TODO: addCreate Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ce"; cmd["t"] = strParent; cmd["p"] = strId; cmd["_data"] = strTag; this.addCommand(cmd); return this; } public xajaxResponse create(string strParent, string strTag, string strId) { return this.addCreate(strParent, strTag, strId); } public xajaxResponse addInsert(string strBefore, string strTag, string strId) { //TODO: addInsert Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ie"; cmd["t"] = strBefore; cmd["p"] = strId; cmd["_data"] = strTag; this.addCommand( cmd); return this; } public xajaxResponse insert(string strBefore, string strTag, string strId) { return this.addInsert(strBefore, strTag, strId); } public xajaxResponse addInsertAfter(string strAfter, string strTag, string strId) { //TODO: addInsertAfter Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ia"; cmd["t"] = strAfter; cmd["p"] = strId; cmd["_data"] = strTag; this.addCommand( cmd); return this; } public xajaxResponse insertAfter(string strAfter, string strTag, string strId) { return this.addInsertAfter(strAfter, strTag, strId); } public xajaxResponse addCreateInput(string strParent, string strType, string strName, string strId) { //TODO: addCreateInput Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ci"; cmd["t"] = strParent; cmd["p"] = strId; cmd["c"] = strType; cmd["_data"] = strName; this.addCommand( cmd); return this; } public xajaxResponse createInput(string strParent, string strType, string strName, string strId) { return this.addCreateInput( strParent, strType, strName, strId); } public xajaxResponse addInsertInput(string strBefore, string strType, string strName, string strId) { //TODO: addInsertInput Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ii"; cmd["t"] = strBefore; cmd["p"] = strId; cmd["c"] = strType; cmd["_data"] = strName; this.addCommand( cmd); return this; } public xajaxResponse insertInput(string strBefore, string strType, string strName, string strId) { return this.addInsertInput( strBefore, strType, strName, strId); } public xajaxResponse addInsertInputAfter(string strAfter, string strType, string strName, string strId) { //TODO: addInsertInputAfter Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "iia"; cmd["t"] = strAfter; cmd["p"] = strId; cmd["c"] = strType; cmd["_data"] = strName; this.addCommand( cmd); return this; } public xajaxResponse insertInputAfter(string strAfter, string strType, string strName, string strId) { return this.addInsertInputAfter( strAfter, strType, strName, strId); } public xajaxResponse addEvent(string strTarget, string strEvent, string strScript) { //TODO: addEvent Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ev"; cmd["t"] = strTarget; cmd["p"] = strEvent; cmd["_data"] = strScript; this.addCommand( cmd); return this; } public xajaxResponse addHandler(string strTarget, string strEvent, string strHandler) { //TODO: addHandler Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "ah"; cmd["t"] = strTarget; cmd["p"] = strEvent; cmd["_data"] = strHandler; this.addCommand( cmd ); return this; } public xajaxResponse addRemoveHandler(string strTarget, string strEvent, string strHandler) { //TODO: addRemoveHandler Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "rh"; cmd["t"] = strTarget; cmd["p"] = strEvent; cmd["_data"] = strHandler; this.addCommand( cmd); return this; } public xajaxResponse removeHandler(string strTarget, string strEvent, string strHandler) { return this.addRemoveHandler(strTarget, strEvent, strHandler); } public xajaxResponse addIncludeScript(string strFileName) { //TODO: addIncludeScript Dictionary<string, string> cmd = new Dictionary<string,string>(); cmd["n"] = "in"; cmd["_data"] = strFileName; this.addCommand(cmd); return this; } public xajaxResponse includeScript(string strFileName) { return this.addIncludeScript(strFileName); } public string getOutput() { //TODO: getOutput StringBuilder objSB = new StringBuilder(); string strEncoding = ""; if (this.strEncoding.Length != 0) { strEncoding = string.Format(" encoding=\"{0}\"", this.strEncoding); } objSB.AppendFormat("<?xml version=\"1.0\"{0} ?><xjx>", strEncoding); if (this.listCommands.Count != 0) { foreach (Dictionary<string, string> aCommand in this.listCommands) { objSB.Append(this._getXMLForCommand(aCommand)); } } objSB.Append("</xjx>"); return objSB.ToString(); } protected string _cmdXML(Dictionary<string, string> setAttributes, string sData) { //TODO: _cmdXML StringBuilder objSB = new StringBuilder(); objSB.Append( "<cmd" ); foreach (string strKey in setAttributes.Keys) { objSB.AppendFormat(" {0}=\"{1}\"", strKey, setAttributes[strKey]); } if ((sData != null) && (sData.IndexOf("<![CDATA[") != -1)) objSB.Append( "><![CDATA[" ).Append( sData ).Append( "]]></cmd>" ); else if (sData.Length != 0) objSB.Append( ">" ).Append( sData ).Append( "</cmd>" ); else objSB.Append( "></cmd>" ); return objSB.ToString(); } protected string _getXMLForCommand(Dictionary<string, string> setAttributes) { //TODO: _getXMLForCommand string strData = ""; bool is_array_mode = false; StringBuilder objSB = new StringBuilder(); objSB.Append( "<cmd" ); foreach( string strKey in setAttributes.Keys) { switch (strKey) { case "_data": strData = setAttributes["_data"]; break; case "_is_array": is_array_mode = true; break; default: if (strKey.Length != 0) { objSB.AppendFormat(" {0}=\"{1}\"", strKey, setAttributes[strKey]); } break; } } if (is_array_mode) { objSB.Append(">") .Append(strData) .Append("</cmd>"); } else { objSB.Append(">") .Append(this._escape(strData)) .Append("</cmd>"); } return objSB.ToString(); } protected string _arrayToXML(List<Dictionary<string, string>> listData) { //TODO: _arrayToXML StringBuilder objSB = new StringBuilder(); objSB.Append( "<xjxobj>"); foreach (Dictionary<string, string> aData in listData) { if (aData.Count > 1) { objSB.Append("<e>"); foreach(string strKey in aData.Keys) { string strKey2 = this.htmlentities(strKey); objSB.Append( "<" ).Append( strKey2 ).Append( ">"); objSB.Append( this._escape( aData[strKey] )); objSB.Append("</").Append( strKey2 ).Append(">"); } objSB.Append("</e>"); } else { foreach (string strKey in aData.Keys) { objSB.Append("<e><k>"); objSB.Append(this._escape(strKey)); objSB.Append("</k><v>"); objSB.Append(this._escape(aData[strKey])); objSB.Append("</v></e>"); } } } objSB.Append("</xjxobj>"); return objSB.ToString(); } public void addCommand(Dictionary<string, string> setAttributes) { //TODO: addCommand this.listCommands.Add( setAttributes ); } protected string _escape(string sData) { //TODO: _escape if ((sData == null) || (sData.Length == 0)) return ""; bool needCDATA = false; { if ((sData.IndexOf("<![CDATA[") != -1) || (sData.IndexOf( "]]>") != -1) || (htmlentities(sData) != sData)) { needCDATA = true; } List<string> listSegments = explode("<![CDATA[", sData); System.Text.StringBuilder objSB = new StringBuilder(); sData = ""; foreach (string strSegment in listSegments) { List<string> listFragments = explode("]]>", strSegment); objSB.Length = 0; foreach (string strFragment in listFragments) { if (objSB.Length != 0) objSB.Append( "]]]]><![CDATA[>" ); objSB.Append( strFragment ); } if (sData != "") sData += "<![]]><![CDATA[CDATA["; sData += objSB.ToString(); } } if (needCDATA) sData = "<![CDATA[" + sData + "]]>"; return sData; } }
檔案:xajax.net.js
- 用途:取代原本的 xajax.js
xajax.net.js
// xajax.net Javascript library :: version 0.2.5 function getXmlDocumentFromString(strXml) { var objXmlDocument = null; if (document.implementation.createDocument) { // Mozilla, create a new DOMParser var parser = new DOMParser(); objXmlDocument = parser.parseFromString(strXml, "text/xml"); } else if (window.ActiveXObject) { // Internet Explorer, create a new XML document using ActiveX // and use loadXML as a DOM parser. objXmlDocument = new ActiveXObject("Microsoft.XMLDOM"); objXmlDocument.async = false; objXmlDocument.loadXML(strXml); } return objXmlDocument; } function Xajax() { this.arrayContainsValue = function(array, valueToCheck) { for (i in array) { if (array[i] == valueToCheck) return true; } return false; }; this.DebugMessage = function(text) { if (text.length > 1000) text = text.substr(0,1000)+"...\n[long response]\n..."; try { if (this.debugWindow == undefined || this.debugWindow.closed == true) { this.debugWindow = window.open('about:blank', 'xajax-debug', 'width=800,height=600,scrollbars=1,resizable,status'); this.debugWindow.document.write('<html><head><title>Xajax debug output</title></head><body><h2>Xajax debug output</h2><div id="debugTag"></div></body></html>'); } debugTag = this.debugWindow.document.getElementById('debugTag'); if (!debugTag) throw new Error(); text = text.replace(/&/g, "&"); text = text.replace(/</g, "<"); text = text.replace(/>/g, ">"); debugTag.innerHTML = ('<b>'+(new Date()).toString()+'</b>: ' + text + '<hr/>') + debugTag.innerHTML; } catch (e) { alert("Xajax Debug:\n " + text); } }; this.workId = 'xajaxWork'+ new Date().getTime(); this.depth = 0; this.responseErrorsForAlert = ["400","401","402","403","404","500","501","502","503"]; //Get the XMLHttpRequest Object this.getRequestObject = function() { if (xajaxDebug) this.DebugMessage("Initializing Request Object.."); var req = null; if (typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { var aVersions = ["Msxml2.XMLHttp.5.0","Msxml2.XMLHttp.4.0","Msxml2.XMLHttp.3.0","Msxml2.XMLHttp","Microsoft.XMLHttp"]; for (var i=0; i<aVersions.length;i++) { try { req = new ActiveXObject(aVersions[i]); break; } catch (e) { req = null; } } } if(!req && window.createRequest) req = window.createRequest(); if (!req) this.DebugMessage("Request Object Instantiation failed."); return req; } // xajax.$() is shorthand for document.getElementById() this.$ = function(sId) { if (!sId) { return null; } var returnObj = document.getElementById(sId); if (!returnObj && document.all) { returnObj = document.all[sId]; } if (xajaxDebug && !returnObj && sId != this.workId) { this.DebugMessage("Element with the id \"" + sId + "\" not found."); } return returnObj; } // xajax.include(sFileName) dynamically includes an external javascript file this.include = function(sFileName) { var objHead = document.getElementsByTagName('head'); var objScript = document.createElement('script'); objScript.type = 'text/javascript'; objScript.src = sFileName; objHead[0].appendChild(objScript); } this.stripOnPrefix = function(sEventName) { sEventName = sEventName.toLowerCase(); if (sEventName.indexOf('on') == 0) { sEventName = sEventName.replace(/on/,''); } return sEventName; } this.addOnPrefix = function(sEventName) { sEventName = sEventName.toLowerCase(); if (sEventName.indexOf('on') != 0) { sEventName = 'on' + sEventName; } return sEventName; } // xajax.addHandler adds an event handler to an element this.addHandler = function(sElementId, sEvent, sFunctionName) { if (window.addEventListener) { sEvent = this.stripOnPrefix(sEvent); this.$(sElementId).addEventListener(sEvent,eval(sFunctionName),false); } else if (window.attachEvent) { sAltEvent = this.addOnPrefix(sEvent); if (this.$(sElementId).attachEvent(sAltEvent,eval(sFunctionName))) window.attachEvent('onunload', function(){xajax.$(sElementId).detachEvent(sAltEvent,eval(sFunctionName));}); } else { sAltEvent = this.addOnPrefix(sEvent); this.$(sElementId)[sAltEvent] = eval(sFunctionName); } } // xajax.removeHandler removes an event handler from an element this.removeHandler = function(sElementId, sEvent, sFunctionName) { if (window.removeEventListener) { sEvent = this.stripOnPrefix(sEvent); this.$(sElementId).removeEventListener(sEvent,eval(sFunctionName),false); } else if (window.detachEvent) { sAltEvent = this.addOnPrefix(sEvent); try { this.$(sElementId).detachEvent(sAltEvent,eval(sFunctionName)); } catch (ignore) {} } else { sAltEvent = this.addOnPrefix(sEvent); this.$(sElementId)[sAltEvent] = null; } } // xajax.create creates a new child node under a parent this.create = function(sParentId, sTag, sId) { var objParent = this.$(sParentId); objElement = document.createElement(sTag); objElement.setAttribute('id',sId); if (objParent) objParent.appendChild(objElement); } // xajax.insert inserts a new node before another node this.insert = function(sBeforeId, sTag, sId) { var objSibling = this.$(sBeforeId); objElement = document.createElement(sTag); objElement.setAttribute('id',sId); objSibling.parentNode.insertBefore(objElement, objSibling); } // xajax.insertAfter inserts a new node after another node this.insertAfter = function(sAfterId, sTag, sId) { var objSibling = this.$(sAfterId); objElement = document.createElement(sTag); objElement.setAttribute('id',sId); objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling); } this.getInput = function(sType, sName, sId) { var Obj; if (!window.addEventListener) { Obj = document.createElement('<input type="'+sType+'" id="'+sId+'" name="'+sName+'">'); } else { Obj = document.createElement('input'); Obj.setAttribute('type',sType); Obj.setAttribute('name',sName); Obj.setAttribute('id',sId); } return Obj; } // xajax.createInput creates a new input node under a parent this.createInput = function(sParentId, sType, sName, sId) { var objParent = this.$(sParentId); var objElement = this.getInput(sType, sName, sId); if (objParent && objElement) objParent.appendChild(objElement); } // xajax.insertInput creates a new input node before another node this.insertInput = function(sBeforeId, sType, sName, sId) { var objSibling = this.$(sBeforeId); var objElement = this.getInput(sType, sName, sId); if (objElement && objSibling && objSibling.parentNode) objSibling.parentNode.insertBefore(objElement, objSibling); } // xajax.insertInputAfter creates a new input node after another node this.insertInputAfter = function(sAfterId, sType, sName, sId) { var objSibling = this.$(sAfterId); var objElement = this.getInput(sType, sName, sId); if (objElement && objSibling && objSibling.parentNode) { objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling); } } // xajax.remove deletes an element this.remove = function(sId) { objElement = this.$(sId); if (objElement && objElement.parentNode && objElement.parentNode.removeChild) { objElement.parentNode.removeChild(objElement); } } //xajax.replace searches for text in an attribute of an element and replaces it //with a different text this.replace = function(sId,sAttribute,sSearch,sReplace) { var bFunction = false; if (sAttribute == "innerHTML") sSearch = this.getBrowserHTML(sSearch); var txt=this.$(sId)[sAttribute]; if (typeof txt == "function") { txt = txt.toString(); bFunction = true; } if (txt.indexOf(sSearch)>-1) { var newTxt = ''; while (txt.indexOf(sSearch) > -1) { x = txt.indexOf(sSearch)+sSearch.length+1; newTxt += txt.substr(0,x).replace(sSearch,sReplace); txt = txt.substr(x,txt.length-x); } newTxt += txt; if (bFunction) { this.$(sId)[sAttribute]=newTxt; } else if (this.willChange(sId,sAttribute,newTxt)) { this.$(sId)[sAttribute]=newTxt; } } } // xajax.getFormValues() builds a query string XML message from the elements of a form object // * The first argument is the id of the form // * The second argument (optional) can be set to true if you want to submit disabled elements // * The third argument (optional) allows you to specify a string prefix that a form element // name must contain if you want that element to be submitted this.getFormValues = function(frm) { var objForm; var submitDisabledElements = false; if (arguments.length > 1 && arguments[1] == true) submitDisabledElements = true; var prefix=""; if(arguments.length > 2) prefix = arguments[2]; if (typeof(frm) == "string") objForm = this.$(frm); else objForm = frm; var sXml = "<xjxquery><q>"; if (objForm && objForm.tagName.toUpperCase() == 'FORM') { var formElements = objForm.elements; for( var i=0; i < formElements.length; i++) { if (!formElements[i].name) continue; if (formElements[i].name.substring(0, prefix.length) != prefix) continue; if (formElements[i].type && (formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false) continue; if (formElements[i].disabled && formElements[i].disabled == true && submitDisabledElements == false) continue; var name = formElements[i].name; if (name) { if (sXml != '<xjxquery><q>') sXml += '&'; if(formElements[i].type=='select-multiple') { for (var j = 0; j < formElements[i].length; j++) { if (formElements[i].options[j].selected == true) sXml += name+"="+encodeURIComponent(formElements[i].options[j].value)+"&"; } } else { sXml += name+"="+encodeURIComponent(formElements[i].value); } } } } sXml +="</q></xjxquery>"; return sXml; } // Generates an XML message that xajax can understand from a javascript object this.objectToXML = function(obj) { var sXml = "<xjxobj>"; for (i in obj) { try { if (i == 'constructor') continue; if (obj[i] && typeof(obj[i]) == 'function') continue; var key = i; var value = obj[i]; if (value && typeof(value)=="object" && this.depth <= 50) { this.depth++; value = this.objectToXML(value); this.depth--; } sXml += "<e><k>"+key+"</k><v>"+value+"</v></e>"; } catch(e) { if (xajaxDebug) this.DebugMessage(e.name+": "+e.message); } } sXml += "</xjxobj>"; return sXml; } // unserializes data structure from xajaxResponse::_buildObjXml() this._nodeToObject = function(node) { if (!node) return ''; // parentNode here is weird, have to tune if (node.nodeName == '#cdata-section' || node.nodeName == '#text') { var data = ""; for (var j=0; j<node.parentNode.childNodes.length; j++) { data += node.parentNode.childNodes[j].data; } return data; } else if (node.nodeName == 'xjxobj') { var data = new Array(); for (var j=0; j<node.childNodes.length; j++) { var child = node.childNodes[j]; var key; var value; if (child.nodeName == 'e') { for (var k=0; k<child.childNodes.length; k++) { if (child.childNodes[k].nodeName == 'k') { key = child.childNodes[k].firstChild.data; } else if (child.childNodes[k].nodeName == 'v') { value = this._nodeToObject(child.childNodes[k].firstChild); } } if (key != null && value != null) { data[key] = value; key = value = null; } } } return data; } } this.loadingFunction = function(){}; this.doneLoadingFunction = function(){}; var loadingTimeout; // Sends a XMLHttpRequest to call the specified PHP function on the server // * sRequestType is optional -- defaults to POST this.call = function(sFunction, aArgs, sRequestType) { var i,r,postData; if (document.body && xajaxWaitCursor) document.body.style.cursor = 'wait'; if (xajaxStatusMessages == true) window.status = 'Sending Request...'; clearTimeout(loadingTimeout); loadingTimeout = setTimeout("xajax.loadingFunction();",400); if (xajaxDebug) this.DebugMessage("Starting xajax..."); if (sRequestType == null) { var xajaxRequestType = xajaxDefinedPost; } else { var xajaxRequestType = sRequestType; } var uri = xajaxRequestUri; var value; switch(xajaxRequestType) { case xajaxDefinedGet:{ var uriGet = uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction); if (aArgs) { for (i = 0; i<aArgs.length; i++) { value = aArgs[i]; if (typeof(value)=="object") value = this.objectToXML(value); uriGet += "&xajaxargs[]="+encodeURIComponent(value); } } uriGet += "&xajaxr=" + new Date().getTime(); uri += uriGet; postData = null; } break; case xajaxDefinedPost:{ postData = "xajax="+encodeURIComponent(sFunction); postData += "&xajaxr="+new Date().getTime(); if (aArgs) { for (i = 0; i <aArgs.length; i++) { value = aArgs[i]; if (typeof(value)=="object") value = this.objectToXML(value); postData = postData+"&xajaxargs[]="+encodeURIComponent(value); } } } break; default: alert("Illegal request type: " + xajaxRequestType); return false; break; } r = this.getRequestObject(); if (!r) return false; r.open(xajaxRequestType==xajaxDefinedGet?"GET":"POST", uri, true); if (xajaxRequestType == xajaxDefinedPost) { try { r.setRequestHeader("Method", "POST " + uri + " HTTP/1.1"); r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } catch(e) { alert("Your browser does not appear to support asynchronous requests using POST."); return false; } } r.onreadystatechange = function() { if (r.readyState != 4) return; if (r.status==200) { if (xajaxDebug) xajax.DebugMessage("Received:\n" + r.responseText); if (r.responseXML && r.responseXML.documentElement) xajax.processResponse(r.responseXML); else { var errorString = "Error: the XML response that was returned from the server is invalid."; errorString += "\nReceived:\n" + r.responseText; trimmedResponseText = r.responseText.replace( /^\s+/g, "" );// strip leading space trimmedResponseText = trimmedResponseText.replace( /\s+$/g, "" );// strip trailing if (trimmedResponseText != r.responseText) errorString += "\nYou have whitespace in your response."; alert(errorString); document.body.style.cursor = 'default'; if (xajaxStatusMessages == true) window.status = 'Invalid XML response error'; } } else { if (xajax.arrayContainsValue(xajax.responseErrorsForAlert, r.status)) { var errorString = "Error: the server returned the following HTTP status: " + r.status; errorString += "\nReceived:\n" + r.responseText; alert(errorString); } document.body.style.cursor = 'default'; if (xajaxStatusMessages == true) window.status = 'Invalid XML response error'; } delete r; r = null; } if (xajaxDebug) this.DebugMessage("Calling "+sFunction +" uri="+uri+" (post:"+ postData +")"); r.send(postData); if (xajaxStatusMessages == true) window.status = 'Waiting for data...'; delete r; return true; } //Gets the text as it would be if it were being retrieved from //the innerHTML property in the current browser this.getBrowserHTML = function(html) { tmpXajax = this.$(this.workId); if (!tmpXajax) { tmpXajax = document.createElement("div"); tmpXajax.setAttribute('id',this.workId); tmpXajax.style.display = "none"; tmpXajax.style.visibility = "hidden"; document.body.appendChild(tmpXajax); } tmpXajax.innerHTML = html; var browserHTML = tmpXajax.innerHTML; tmpXajax.innerHTML = ''; return browserHTML; } // Tests if the new Data is the same as the extant data this.willChange = function(element, attribute, newData) { if (!document.body) { return true; } if (attribute == "innerHTML") { newData = this.getBrowserHTML(newData); } elementObject = this.$(element); if (elementObject) { var oldData=this.$(element)[attribute]; if (newData !== oldData) return true; } return false; } //Returns the source code of the page after it's been modified by xajax this.viewSource = function() { return "<html>"+document.getElementsByTagName("HTML")[0].innerHTML+"</html>"; } //Process XML xajaxResponses returned from the request this.processResponse = function(xml) { clearTimeout(loadingTimeout); if (typeof this.doneLoadingFunction != "undefined") this.doneLoadingFunction(); if (typeof xajaxStatusMessages != "undefined") if (xajaxStatusMessages == true) window.status = 'Processing...'; var tmpXajax = null; if (xml.documentElement == null) xml = getXmlDocumentFromString(xml); xml = xml.documentElement; if (xml == null) return; var skipCommands = 0; for (var i=0; i<xml.childNodes.length; i++) { if (skipCommands > 0) { skipCommands--; continue; } if (xml.childNodes[i].nodeName == "cmd") { var cmd; var id; var property; var data; var search; var type; var before; var objElement = null; for (var j=0; j<xml.childNodes[i].attributes.length; j++) { if (xml.childNodes[i].attributes[j].name == "n") { cmd = xml.childNodes[i].attributes[j].value; } else if (xml.childNodes[i].attributes[j].name == "t") { id = xml.childNodes[i].attributes[j].value; } else if (xml.childNodes[i].attributes[j].name == "p") { property = xml.childNodes[i].attributes[j].value; } else if (xml.childNodes[i].attributes[j].name == "c") { type = xml.childNodes[i].attributes[j].value; } } if (xml.childNodes[i].childNodes.length > 1 && (xml.childNodes[i].firstChild.nodeName == "#cdata-section" || xml.childNodes[i].firstChild.nodeName == '#text')) { data = ""; for (var j=0; j<xml.childNodes[i].childNodes.length; j++) { data += xml.childNodes[i].childNodes[j].data; } } else if (xml.childNodes[i].firstChild && xml.childNodes[i].firstChild.nodeName == 'xjxobj') { if (typeof this._nodeToObject != "undefined") data = this._nodeToObject(xml.childNodes[i].firstChild); else data = xajax._nodeToObject(xml.childNodes[i].firstChild); objElement = "XJX_SKIP"; } else if (xml.childNodes[i].childNodes.length > 1) { for (var j=0; j<xml.childNodes[i].childNodes.length; j++) { if (xml.childNodes[i].childNodes[j].childNodes.length > 1 && (xml.childNodes[i].childNodes[j].firstChild.nodeName == "#cdata-section" || xml.childNodes[i].childNodes[j].firstChild.nodeName == "#text")) { var internalData = ""; for (var k=0; k<xml.childNodes[i].childNodes[j].childNodes.length;k++) { internalData+=xml.childNodes[i].childNodes[j].childNodes[k].nodeValue; } } else { var internalData = xml.childNodes[i].childNodes[j].firstChild.nodeValue; } if (xml.childNodes[i].childNodes[j].nodeName == "s") { search = internalData; } if (xml.childNodes[i].childNodes[j].nodeName == "r") { data = internalData; } } } else if (xml.childNodes[i].firstChild) data = xml.childNodes[i].firstChild.nodeValue; else data = ""; if ((objElement != "XJX_SKIP") && (typeof id != "undefined")) { if (typeof this.$ != "undefined") objElement = this.$(id); else objElement = xajax.$(id); } var cmdFullname; try { if (cmd=="cc") { cmdFullname = "addConfirmCommands"; var confirmResult = confirm(data); if (!confirmResult) { skipCommands = id; } } if (cmd=="al") { cmdFullname = "addAlert"; alert(data); } else if (cmd=="js") { cmdFullname = "addScript/addRedirect"; eval(data); } else if (cmd=="jc") { cmdFullname = "addScriptCall"; var scr = id + '('; if (data[0] != null) { scr += 'data[0]'; for (var l=1; l<data.length; l++) { scr += ',data['+l+']'; } } scr += ');'; eval(scr); } else if (cmd=="in") { cmdFullname = "addIncludeScript"; if (typeof this.include != "undefined") this.include(data); else xajax.include(data); } else if (cmd=="as") { cmdFullname = "addAssign/addClear"; if (typeof this.willChange != "undefined") { if (this.willChange(id,property,data)) { objElement[property]=data; } } else { if (xajax.willChange(id,property,data)) { objElement[property]=data; } } } else if (cmd=="ap") { cmdFullname = "addAppend"; objElement[property]+=data; } else if (cmd=="pp") { cmdFullname = "addPrepend"; objElement[property]=data+objElement[property]; } else if (cmd=="rp") { cmdFullname = "addReplace"; if (typeof this.replace != "undefined") this.replace(id,property,search,data) else xajax.replace(id,property,search,data) } else if (cmd=="rm") { cmdFullname = "addRemove"; if (typeof this.replace != "undefined") this.remove(id); } else if (cmd=="ce") { cmdFullname = "addCreate"; this.create(id,data,property); } else if (cmd=="ie") { cmdFullname = "addInsert"; this.insert(id,data,property); } else if (cmd=="ia") { cmdFullname = "addInsertAfter"; this.insertAfter(id,data,property); } else if (cmd=="ci") { cmdFullname = "addCreateInput"; if (typeof this.createInput != "undefined") this.createInput(id,type,data,property); else xajax.createInput(id,type,data,property); } else if (cmd=="ii") { cmdFullname = "addInsertInput"; if (typeof this.insertInput != "undefined") this.insertInput(id,type,data,property); else xajax.insertInput(id,type,data,property); } else if (cmd=="iia") { cmdFullname = "addInsertInputAfter"; if (typeof this.insertInputAfter != "undefined") this.insertInputAfter(id,type,data,property); else xajax.insertInputAfter(id,type,data,property); } else if (cmd=="ev") { cmdFullname = "addEvent"; if (typeof this.addOnPrefix != "undefined") property = this.addOnPrefix(property); else property = xajax.addOnPrefix(property); this.$(id)[property]= eval("function(){"+data+";}"); } else if (cmd=="ah") { cmdFullname = "addHandler"; if (typeof this.addHandler != "undefined") this.addHandler(id, property, data); else xajax.addHandler(id, property, data); } else if (cmd=="rh") { cmdFullname = "addRemoveHandler"; if (typeof this.removeHandler != "undefined") this.removeHandler(id, property, data); else xajax.removeHandler(id, property, data); } } catch(e) { if (xajaxDebug) alert("While trying to '"+cmdFullname+"' (command number "+i+"), the following error occured:\n" + e.name+": "+e.message+"\n" + (id&&!objElement?"Object with id='"+id+"' wasn't found.\n":"")); } delete objElement; delete cmd; delete cmdFullname; delete id; delete property; delete search; delete data; delete type; delete before; delete internalData; delete j; delete k; } } delete xml; delete i; document.body.style.cursor = 'default'; if (typeof xajaxStatusMessages != "undefined") if (xajaxStatusMessages == true) window.status = 'Done'; } } var xajax = new Xajax(); xajaxLoaded = true; xajaxDebug = false;
使用範例
- 新增 VS 2005 的專案時,需選擇 ASP.NET AJAX 新專案
檔案:Web.config
Web.config
<?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" /> <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> </sectionGroup> </sectionGroup> </sectionGroup> </configSections> <system.web> <pages> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </controls> </pages> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <compilation debug="false"> <assemblies> <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </assemblies> </compilation> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </httpModules> </system.web> <system.web.extensions> <scripting> <webServices> <!-- Uncomment this line to customize maxJsonLength and add a custom converter --> <!-- <jsonSerialization maxJsonLength="500"> <converters> <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/> </converters> </jsonSerialization> --> <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. --> <!-- <authenticationService enabled="true" requireSSL = "true|false"/> --> <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and writeAccessProperties attributes. --> <!-- <profileService enabled="true" readAccessProperties="propertyname1,propertyname2" writeAccessProperties="propertyname1,propertyname2" /> --> </webServices> <!-- <scriptResourceHandler enableCompression="true" enableCaching="true" /> --> </scripting> </system.web.extensions> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated" /> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </handlers> </system.webServer> </configuration>
檔案:Default.aspx
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server" action="#"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="xajax.net.js" /> </Scripts> </asp:ScriptManager> <br /> <input type="button" onclick="PageMethods.doAdd(39, 571, xajax.processResponse);" id="btnAdd" value="Click Me" /> <input type="button" style="display: none" onclick="PageMethods.doReset(xajax.processResponse);" id="btnReset" value="Reset" /> <p id="answer"> </p> </div> </form> </body> </html>
檔案:Default.aspx.cs
Default.aspx.cs
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Services; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] static public string doAdd(int a, int b) { xajaxResponse xajax = new xajaxResponse(); int ret = a + b; xajax.assign("answer", "innerHTML", ret.ToString()); xajax.assign("btnAdd", "style.display", "none"); xajax.assign("btnReset", "style.display", "block"); return xajax.ToString(); } [WebMethod] static public string doReset() { xajaxResponse xajax = new xajaxResponse(); xajax.clear("answer", "innerHTML"); xajax.assign("btnReset", "style.display", "none"); xajax.assign("btnAdd", "style.display", "block"); return xajax.ToString(); } }