網頁開發的新利器-AJAX 文/沈炳宏 -----box----- 程式 1 JavaScript: function getXMLHTTP() { var req = false; if(window.XMLHttpRequest) { try { req = new XMLHttpRequest(); } catch(e) {} } else if(window.ActiveXObject) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } } // end if return req; } // end function -----box----- -----box----- 程式 2 JavaScript: function updateCityState() { if (!isWorking) { var zipValue = document.getElementById("zip").value; xmlhttp.open("GET", url + escape(zipValue), true); isWorking = true; xmlhttp.onreadystatechange = handleHttpResponse; xmlhttp.send(null); } } HTML: -----box----- -----box----- 程式 3 function handleHttpResponse() { if (xmlhttp.readyState == 4) { isWorking = false; if (xmlhttp.responseText.indexOf('invalid') == -1) { var xmlDocument = xmlhttp.responseXML; var city = xmlDocument. getElementsByTagName('city').item(0). firstChild.data; var state = xmlDocument. getElementsByTagName('state').item(0). firstChild.data; document.getElementById('city').value = city; document.getElementById('state').value = state; } } } -----box----- -----box----- 程式 4 private void btnSubmit_Click( object sender, System.EventArgs e) { if (txtUser.Text == "Bill" && txtPass.Text == "Bill") { lblMessage.Text = " 歡迎光臨," + txtUser.Text + ""; } else { lblMessage.Text = " 登入失敗!"; } } -----box----- -----box----- 程式 5 -----box----- -----box----- 程式 6
請輸入帳號
帳號:
密碼:
-----box----- -----box----- 程式 7 Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1)); -----box----- -----box----- 程式 8 [Ajax.AjaxMethod] public bool LoginUserOnServer( string user,string pass) { System.Threading.Thread.Sleep(5000); if (user == "Bill" && pass == "Bill") { return true; } else { return false; } } [Ajax.AjaxMethod] public static MyClass GetServerTime() { MyClass c = new MyClass(); return c; } } [Serializable()] public class MyClass { public string _strtime = System.DateTime.Now.ToLongTimeString(); public string strtime { get { return _strtime; } } } -----box-----