閱讀841 返回首頁    go 阿裏雲 go 技術社區[雲棲]


1.使用XMLHttPRequest控件異步獲取數據

 知識點:

①根據瀏覽器的不同實例化XMLHttpRequest對象;

②發送一個異步請求的步驟;

③如何處理每次回調的函數;

完整代碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="01_XmlHttpRequest.aspx.cs" Inherits="XmlHttpRequest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml" > <head runat="server"> <title>ASP.NET AJAX In Action - XmlHttpRequest</title> </head> <body> <form runat="server"> <div> <span >Loading...<br /> <!--這裏用按鈕觸發異步回調事件--> </span><input type="button" value="觸發異步調用,調用Welcome.htm的內容" /> </div> </form> <script type="text/javascript"> <!-- var xmlHttp = null; window.onload = function() { loadXmlHttp(); //sendRequest("Welcome.htm"); } //【1】根據瀏覽器版本實例化xmlHttp對象 function loadXmlHttp() { if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, Opera等瀏覽器 xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE 5.x and 6版本的微軟瀏覽器 } catch (e){} } } //【2】發送一個異步請求的步驟; function sendRequest(url) { if (xmlHttp) { // ①打開異步連接 xmlHttp.open("GET", url, true); // true = async // ②指定回調函數 xmlHttp.onreadystatechange = onCallback; // [可選]Specify form data in request body xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // ③發送異步請求 xmlHttp.send(null); } } //【3】每次異步請求的就緒狀態改變時都會調用的回調函數; function onCallback() { // ①查看完成了的就緒狀態 if (xmlHttp.readyState == 4) { // ②狀態碼200表示成功,404表示沒有文件錯誤 if (xmlHttp.status == 200) { // ③顯示請求結果 var r = document.getElementById('results'); r.innerHTML = xmlHttp.responseText; } else { alert('Error: ' + xmlHttp.status); } } } // --></script> </body> </html>

welcome.htm頁麵代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml" > <head> <title>Welcome</title> </head> <body> <div>Welcome to ASP.NET AJAX In Action!</div> </body> </html>

最後更新:2017-04-02 04:00:24

  上一篇:go 反射
  下一篇:go 堆排序