今天回顾了一下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调用,获取到数据。仅供参考。