JS写的AJAX调用
时间:2010-10-09 来源:canyan3073
今天回顾了一下js的ajax调用,写了个小示例:
JS代码:
- <script type="text/javascript">
- //调用函数
- function getMsg() {
- createXMLHttpRequest();
- var name = "Marx";
- var url = "hdHelloWorld.ashx?Name=" + name; //URL地址:这里访问的是一个一般处理程序文件
- xmlReq.open("GET", url, false); //以GET的方式访问
- xmlReq.onreadystatechange = OnMessageBack; //设置回调函数
- xmlReq.send(null); //发送请求
- }
- //回调函数
- function OnMessageBack() {
- if (xmlReq.readyState == 4) {
- if (xmlReq.status == 200) {//调用成功,返回结果
- sum = xmlReq.responseText;
- document.getElementById("div1").innerHTML = sum;//将返回的结果写到DIV中
- }
- }
- }
- // 创建一个ActiveXObject 对象使现局部请求到服务器
- function createXMLHttpRequest() {
- if (window.XMLHttpRequest) {
- xmlReq = new XMLHttpRequest();
- if (xmlReq.overrideMimeType)
- xmlReq.overrideMimeType('text/xml');
- }
- else if (window.ActiveXObject) {
- try {
- xmlReq = new ActiveXObject('Msxml2.XMLHTTP');
- }
- catch (e) {
- try {
- xmlReq = new ActiveXObject('Microsoft.XMLHTTP');
- }
- catch (e) {
- }
- }
- }
- }
- </script>
一般处理程序hdHelloWorld.ashx中的代码:
- public void ProcessRequest (HttpContext context) {
- string name = context.Request.QueryString["Name"];
- context.Response.Write("Hello " + name+"!");
- }
HTML代码:
- <input type="button" value="GetMsg" onclick="getMsg();" />
- <div id="div1"></div>
点击“GetMsg”按钮,就会通过ajax调用,获取到数据。仅供参考。
相关阅读 更多 +