JS寫的AJAX調用

今天回顧了一下js的ajax調用,寫了個小示例:

JS代碼:

  1. <script type="text/javascript"
  2.         //調用函數  
  3.         function getMsg() { 
  4.             createXMLHttpRequest(); 
  5.             var name = "Marx"
  6.             var url = "hdHelloWorld.ashx?Name=" + name;    //URL地址:這裏訪問的是一個一般處理程序文件 
  7.             xmlReq.open("GET", url, false);    //以GET的方式訪問  
  8.             xmlReq.onreadystatechange = OnMessageBack;      //設置回調函數 
  9.             xmlReq.send(null);        //發送請求 
  10.         } 
  11.         //回調函數 
  12.         function OnMessageBack() { 
  13.             if (xmlReq.readyState == 4) { 
  14.                 if (xmlReq.status == 200) {//調用成功,返回結果 
  15.                     sum = xmlReq.responseText; 
  16.                     document.getElementById("div1").innerHTML = sum;//將返回的結果寫到DIV中 
  17.                 } 
  18.             } 
  19.         } 
  20.  
  21.         // 創建一個ActiveXObject 對象使現局部請求到服務器 
  22.         function createXMLHttpRequest() { 
  23.             if (window.XMLHttpRequest) { 
  24.                 xmlReq = new XMLHttpRequest(); 
  25.                 if (xmlReq.overrideMimeType) 
  26.                     xmlReq.overrideMimeType('text/xml'); 
  27.             } 
  28.             else if (window.ActiveXObject) { 
  29.                 try { 
  30.                     xmlReq = new ActiveXObject('Msxml2.XMLHTTP'); 
  31.                 } 
  32.                 catch (e) { 
  33.                     try { 
  34.                         xmlReq = new ActiveXObject('Microsoft.XMLHTTP'); 
  35.                     } 
  36.                     catch (e) { 
  37.  
  38.                     } 
  39.                 } 
  40.             } 
  41.         } 
  42.     </script> 

一般處理程序hdHelloWorld.ashx中的代碼:

  1. public void Proce***equest (HttpContext context) { 
  2.       string name = context.Request.QueryString["Name"]; 
  3.       context.Response.Write("Hello " + name+"!"); 
  4.   } 

HTML代碼:

  1. <input type="button" value="GetMsg" onclick="getMsg();" /> 
  2. <div id="div1"></div> 

 

點擊“GetMsg”按鈕,就會通過ajax調用,獲取到數據。僅供參考。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章