Ajax基本原理

Ajax基本原理

//根据不同浏览器使用响应的方式来创建异步对象
function createXmlHttp() {
    var xhobj = false;
    try {
        xhobj = new ActiveXObject("Msxml2.XMLHTTP");
         } 
    catch (e) {
        try {
            xhobj = new ActiveXObject("Microsoft.XMLHTTP");
             }
        catch (e2) {
            xhobj = false;
        }
    }
    if(!xhobj&&typeof(XMLHttpRequest)!='undefined')
    {
      xhobj=new XMLHttpRequest();
  }
  return xhobj;
} 

 

页面FirstAjaxForFun.aspx

<head runat="server">
    <title>第一个Ajax应用</title>
    <script src="../Scripts/common.js" type="text/javascript"></script>
    <script type="text/javascript">
        var xhr = false;
        function GetData() {
          //1.创建对象
            xhr = createXmlHttp();
            //2.设置请求参数
            xhr.open("GET", "FirstAjaxForFun.ashx", true);
            //2.1设置浏览器不使用缓存
            xhr.setRequestHeader("If-Modified-Since", "0");
            //3.设置回到函数
            xhr.onreadystatechange = function () {
              
                if (xhr.readyState == 4) {//当服务器已经将数据回到浏览器
                    if (xhr.status == 200) {//如果还回的响应报文状态码为290,才表示服务器端运行正常
                        //                        alert(xhr.responseText);
                        document.getElementById("gisDiv").innerHTML = xhr.responseText;
                    }
                    else {
                        document.getElementById("gisDiv").innerHTML = xhr.responseText;
                   
                       alert("系统繁忙 请联系管理员")
                    }
                }
            }
            xhr.send(null);//用GET方法参数就写null;异步对象发送请求
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <input type="button" onclick="GetData()" value="调用异步函数" />
      <div id="gisDiv"></div>
    </div>
    </form>
</body>
</html>

一般处理程序这里是相对于异步对象请求的服务器FirstAjaxForFun.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WEBUI.AJAXTEST
{
    /// <summary>
    /// FirstAjaxForFun1 的摘要说明
    /// </summary>
    public class FirstAjaxForFun1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            System.Threading.Thread.Sleep(2000);
            
            context.Response.Write("Hello World "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted on 2013-01-10 22:29  C#+sql  阅读(296)  评论(0编辑  收藏  举报