記錄一段AJAX的基本寫法,代碼加註釋,很多人認為它神秘,其實看了就明白了
這裡用.NET的ASPX做返回處理的服務端
JS代碼,調用方法
<script type ="text/javascript">
var request = false;
try ...{
request = new XMLHttpRequest();//非微軟瀏覽器
} catch (trymicrosoft) ...{
try ...{
request = new ActiveXObject("Msxml2.XMLHTTP");//微軟IE
} catch (othermicrosoft) ...{
try ...{
request = new ActiveXObject("Microsoft.XMLHTTP");//微軟其他
} catch (failed) ...{
request = false;
}
}
}
if (!request)//老式瀏覽器不支援XMLHttpRequest對象的
alert("Error initializing XMLHttpRequest!");
function getCustomerInfo() ...{
var phone = document.getElementById("Text1").value;//擷取表單上Text摸值
var url = "http://localhost:14379/WebHtmlPartDynamic/Default2.aspx?phone="+escape(phone);//請求的網頁
request.open("GET", url, true);//建立請求:GET方式,地址,TRUE為非同步呼叫
request.onreadystatechange = updatePage;//伺服器處理完畢調用哪個方法
request.send(null);//發送請求(一般不發送安全資訊和XML為NULL)
}
function updatePage() ...{
if(request.readyState ==4)//判斷HTTP請求的就緒狀態,這裡4是最後一狀態
if (request.status == 200)//請求正常的狀態代碼為200(返回錯誤串連的404類似的一種表示)
...{
var dh = request.responseText;
alert(dh);
}
else if (request.status == 404)//以下為錯誤檢查
alert("Request URL does not exist")
else
alert("Error: status code is " + request.status);
}
</script>
HTML代碼 如何調用
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" />
<input id="Submit1" type="submit" value="submit" onclick = "getCustomerInfo()" /></div>
</form>
</body>
ASPX裡寫的,做為響應AJAX請求的處理部分
protected void Page_Load(object sender, EventArgs e)
...{
if (!IsPostBack)
...{
string str = Request.QueryString["phone"];
Response.Write(str);
Response.Flush();
Response.End();
}
}