前端javascript
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script type="text/javascript"> onload = function () { var userName = document.getElementById("tuserName"); var userPwd = document.getElementById("tuserPwd"); var btnGet = document.getElementById("btnGet"); var btnPost = document.getElementById("btnPost"); var divShow = document.getElementById("divDes"); btnGet.onclick = function () { //發送異步請求 //一、判斷是否IE5 IE6 由於IE五、6只支持ActiveXObject var xhr; if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr=new ActiveXObject("Microsoft.XMLHTTP") } //open(method---請求的方法【GET或POSt】,url--請求的頁面,asyc 是否異步 ,user請求的用戶名,pwd密碼 )方法 //注:Get請求參數經過 地址 來傳送, var url = "index.ashx?name=" + userName.value + "&password=" + userPwd.value+"&time="+Date.now.toString(); xhr.open("Get", url, true); //三、發送異步請求 xhr.send(); //四、監聽請求狀態 onreadystatechange 狀態改變事件 4爲加載成功 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { //若是後臺返回成功 if (xhr.responseText = "OK") { //location.href = "http://www.baidu.com"; divShow.innerHTML = xhr.responseText; } else { divShow.innerHTML = xhr.responseText; } } } } btnPost.onclick = function () { alert("btnPost") } } </script> </head> <body> <input type="text" id="tuserName" /> <input type="text" id="tuserPwd"/> <input type="button" id="btnGet" value="btnGet" /> <input type="button" id="btnPost" value="btnPost"/> <div id="divDes"> </div> </body> </html>
後臺html
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Ajax練習 { /// <summary> /// index 的摘要說明 /// </summary> public class index : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //獲取請求到的參數 string name= context.Request["name"]; string password = context.Request["password"]; //執行 處理 if (name == password) { //返回結果 context.Response.Write("OK"); } else { //返回結果 context.Response.Write("NG"); } } public bool IsReusable { get { return false; } } } }