Ajax with ASP.NET--含常用javascript(转)

http://blog.csdn.net/smartkernel/archive/2007/07/28/1713112.aspx

---------------------------------------------------------------------------------------------------- 
0001:
    Ajax:Asynchronous JavaScript And XML
----------------------------------------------------------------------------------------------------
0002:
    JSON:JavaScript Object Notation
----------------------------------------------------------------------------------------------------
0003:
    DHTML是三中技术的融合:HTML、CSS和JavaScript。
----------------------------------------------------------------------------------------------------
0004:
    直接在元素中使用JavaScript的情况:
    <body onload = "window.status = '加载完成!'">或者<body onload = "javascript:window.status = '加载完成!'">
----------------------------------------------------------------------------------------------------
0005:
    确认对话框的使用:
    <script language = "javascript">
        var isConfirm = window.confirm("确认么?");
        if(isConfirm == true)
        {
            alert("确认!");
        }
        else
        {
            alert("取消!");
        }
    </script>
----------------------------------------------------------------------------------------------------
0006:
    自动导航到某个网页:window.location.href = "http://www.126.com";
----------------------------------------------------------------------------------------------------
0007:
    打开确认:
    <script language = "javascript">
        function clickHandler()
        {
            var isConfirm = window.confirm("确认么?");
            return isConfirm;
        }
    </script>
    <a href = "http://www.126.com" onclick = "javascript:return clickHandler()">126电子邮箱</a>
----------------------------------------------------------------------------------------------------
0008:
    确认提交:
    <form onsubmit = "return window.confirm("确认么?");">
        <input id="Submit1" type="submit" value="submit" />
    </form>
----------------------------------------------------------------------------------------------------
0009:
    防止事件冒泡的方法:form的单击时间不会传递给body
    <body onclick = "alert('body')">
        <form onclick = "event.cancelBubble = true;alert('form')">
                你好
        </form>
    </body>
----------------------------------------------------------------------------------------------------
0010:
    方法中this的指代:
    <script language = "javascript">
        function clickHandler(obj)
        {
            //this代表对触发此事件的对象的引用
            alert(obj.href);
        }
    </script>
    <a href = "http://www.126.com" onclick = "clickHandler(this);return false;">126邮箱</a>
----------------------------------------------------------------------------------------------------
0011:
    select控件的使用:
    <select id="Select1" style="width: 200px">
        <option selected="selected"></option>
    </select>
    <input id="Text1" type="text" />
    <input id="Button1" type="button" value="button" onclick = "javascript:clickHandler();"/>
   
    <script language = "javascript">
        function clickHandler()
        {
            var myText = document.getElementById("Text1").value;
            var mySelect = document.getElementById("Select1");
            mySelect[mySelect.length] = new Option(myText,myText);
            mySelect.selectedIndex = mySelect.length - 1;
        }
    </script>
----------------------------------------------------------------------------------------------------
0012:
    innerHTML属性:
    <span id = "mySpan">
        <input id="Button1" type="button" value="button" onclick = "javascript:clickHandler();"/>
    </span>
    <script language = "javascript">
        function clickHandler()
        {
            var mySpan = document.getElementById("mySpan");
            alert(mySpan.innerHTML);
        }
    </script>
----------------------------------------------------------------------------------------------------
0013:
    隐藏和显示的实现:
    <div id = "myDiv" style = "display:block">
        你好
    </div>
   
    <input id="Button1" type="button" value="button" onclick = "javascript:clickHandler();"/>
   
    <script language = "javascript">
        function clickHandler()
        {
            var myDiv = document.getElementById("myDiv");
            if(myDiv.style.display === "block")
            {
                myDiv.style.display = "none";
            }
            else
            {
                myDiv.style.display = "block";
            }
        }
    </script>
----------------------------------------------------------------------------------------------------
0014:
    覆盖右键单击事件:注意,只有单击“你好”才起作用。
    <body oncontextmenu = "javascript:oncontextmenuHandler();return false;"
    onclick = "javascript:onclickHandler();return false;">  
        你好
        <div id = "myMenu" style = "position:absolute; z-index:999; visibility:hidden;
        border:1px solid #000080; background-color:#4000c0; color:#FFFF00;">
            自定义的右键菜单
        </div>
        <script language = "javascript">
            function oncontextmenuHandler()
            {
                var myMenu = document.getElementById("myMenu");
                myMenu.style.left = event.clientX;
                myMenu.style.top = event.clientY;
                myMenu.style.visibility = "visible";
            }
            function onclickHandler()
            {
                var myMenu = document.getElementById("myMenu");
                myMenu.style.visibility = "hidden";
            }
        </script>
    </body>
----------------------------------------------------------------------------------------------------
0015:
    JavaScript代码的标准写法:
    <script type ="text/javascript">
        <!--
        alert("hello");
        -->
    </script>
----------------------------------------------------------------------------------------------------
0016:
    HTML是不区分大小写的,但是XHTML和JavaScript都是区分大小写的。
----------------------------------------------------------------------------------------------------
0017: 
    获得变量的类型:
    var myVar = 5;
    alert(typeof myVar);
----------------------------------------------------------------------------------------------------
0018:
    数组的使用:
    var myArray = new Array();
    for(var i = 0;i < 10;i++)
    {
        myArray[i] = i*i;
    }
    for(var i = 0;i < 10;i++)
    {
        document.writeln(myArray[i]);
    }
----------------------------------------------------------------------------------------------------
0019:
    检索一个对象所有的属性和事件:
    for( var member in document )
    {
        document.write(member + "<br>");
    }
----------------------------------------------------------------------------------------------------
0020:
    动态增加或删除一个对象的属性:
    var o = new Object();
    //新增加了一个属性
    o.Name = "对象";
    document.write(o.Name + "<br>");
    //删除了一个属性
    delete o.Name;
    document.write(o.Name);
----------------------------------------------------------------------------------------------------
0021:
    对象的属性可以通过键值对的方式访问:
    var o = new Object();
    o.Name = "对象";
    document.write(o["Name"]);
----------------------------------------------------------------------------------------------------
0022:
    键值对的方式声明一个对象的属性和方法:
    var newObject =
    {
        name:"对象",
        toString:function(msg)
        {
            alert(msg);
        },
        say:function()
        {
            alert(this.name);
        }
    }
    newObject.toString("呵呵");
    newObject.say();
----------------------------------------------------------------------------------------------------
0023:
    实现一个Person类:
    function Person(name,age)
    {
        if(name.constructor == String)
        {
            this.Name = name;
        }
        if(age.constructor == Number)
        {
            this.Age = age;
        }
    }
    Person.prototype.Say = function()
    {
        alert("我是:" + this.Name + ";今年" + this.Age);
    }  

    var aPerson = new Person("小六",25);
    aPerson.Say();
    alert(aPerson.Name);
----------------------------------------------------------------------------------------------------
0024:
    修改内置类的属性或方法:
    String.prototype.toString = function()
    {
        return "长度是:" + this.length;
    }
   
    var str = "你好";
    document.write(str.toString());
----------------------------------------------------------------------------------------------------
0025:
    类继承的实现:
    function Person(name,age)
    {
        this.Name = name;
        this.Age = age;
    }
    Person.prototype.Say = function()
    {
        alert(this.Name + "|" + this.Age);
    }
   
    function WaiXingRen(name,age,love)
    {
        this.Love = love;
        this.Name = name;
        this.Age = age;
    }
    WaiXingRen.prototype = new Person();
    WaiXingRen.prototype.WhichLove = function()
    {
        alert(this.Love);
    }
   
    var aWaiXingRen = new WaiXingRen("小李",34,"蔬菜");
    aWaiXingRen.Say();
    aWaiXingRen.WhichLove();
    alert(aWaiXingRen.Name);
----------------------------------------------------------------------------------------------------
0026:
    判断浏览器是否支持DOM Level 1级:
    alert(document.implementation.hasFeature("HTML","1.0"));
----------------------------------------------------------------------------------------------------
0027:
    通过JavaScript控制内容:DOM的方式
    <h1 id = "myH1">世界</h1>
    <script type ="text/javascript">
    var myH1 = document.getElementById("myH1");
    myH1.firstChild.data = "你好";
    </script>
    注意:JavaScript代码必须在元素的后面出现,否则,元素还没有加载完成,这个时候是没有对象的引用的。
如果写在元素的前面,可以使用这个代码:
    <script type ="text/javascript">
    window.onload = function()
    {
        var myH1 = document.getElementById("myH1");
        myH1.firstChild.data = "你好";
    }
    </script>
----------------------------------------------------------------------------------------------------
0028:
    DOM的创建方法:
    document.createAttribute("width");
    document.createElement("H1");
    document.createTextNode("世界你好!");

    DOM的插入和添加方法:
    aNode.insertBefore(newChildNode,referenceNode);
    aNode.appendChild(newChildNode);

    DOM的删除和替换:
    aNode.removeChild(childNode);
    aNode.replaceChild(newNode,nodeToReplace);
    aNode.cloneNode(isDeepClone);

    DOM的属性:
    aNode.nodeName;
    aNode.nodeValue;//常用于获取或设置文本属性的值
    aNode.nodeType;//1,Element;2,Attribute;3,Text;4,CDATA Section;
                   //5,Entity Reference;6,Entity;7,Processing Instruction;8,Comment
                   //9,Document;10,Document Type;11,Document Fragment;12,Notation
    aNode.parentNode;
    aNode.childNodes;
    aNode.firstChild;
    aNode.lastChild;
    aNode.previousSibling;
    aNode.nextSibling;
    aNode.attributes;
    aNode.ownerDocument;
----------------------------------------------------------------------------------------------------
0029:
    style属性与直接设置属性的区别:有连接字符-的全部去掉,然后第二个单词的第一个字符大写。
    <h1 id = "myH1" style ="background-color:Green">世界</h1>
    <script type ="text/javascript">
        var myH1 = document.getElementById("myH1");
        myH1.style.backgroundColor = "Red";
    </script>
----------------------------------------------------------------------------------------------------
0030:
    创建XMLHttpRequest对象的方法:
    function createXMLHttpRequest()
    {
        var xmlHttp;
        if( window.XMLHttpRequest )
        {
            //非IE浏览器
            xmlHttp = new XMLHttpRequest();
        }
        else
        {
            //IE浏览器的不同版本
            try
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(err)
            {
                xmlHttp = new AvtiveXObject("Msxml2.XMLHTTP");
            }
        }
        return xmlHttp;
    }
----------------------------------------------------------------------------------------------------
0031:
    实现一个异步请求的简单例子:
    //创建一个XMLHttpRequest对象
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        //true代表异步请求
        xmlHttp.open("GET","Data.xml",true);
        //回调函数
        xmlHttp.onreadystatechange = function()
        {
            //0,未初始化;1,正在加载;2,加载完成;3,交互;4,完成
            if(xmlHttp.readyState == 4)
            {
                alert(xmlHttp.responseText);
            }
        }
        //发送请求,因为使用的是GET方法,所以不需要传送参数
        xmlHttp.send(null);
    }
----------------------------------------------------------------------------------------------------
0032:
    XMLHttpRequest对象有个安全问题,其所请求的地址必须和当前代码所在的地址在同一个域中。
----------------------------------------------------------------------------------------------------
0033:
    用控件来处理异步请求返回的数据:
    <div id = "myPanel">{}</div>
    <script type ="text/javascript">
        //创建一个XMLHttpRequest对象
        var xmlHttp = createXMLHttpRequest();
        if(xmlHttp)
        {
            //true代表异步请求
            xmlHttp.open("GET","Data.xml",true);
            //回调函数
            xmlHttp.onreadystatechange = function()
            {
                //0,未初始化;1,正在加载;2,加载完成;3,交互;4,完成
                if(xmlHttp.readyState == 4)
                {
                    var myPanel = document.getElementById("myPanel");
                    //注意:div中的{}是不能缺少的,这个就是0所代表的元素 
                    myPanel.childNodes[0].nodeValue = xmlHttp.responseText;
                }
            }
            //发送请求,因为使用的是GET方法,所以不需要传送参数
            xmlHttp.send(null);
        }
    </script>
----------------------------------------------------------------------------------------------------
0034:
    使用XPath处理异步请求的XML文档:
    <div id = "myPanel">{}</div>
    <script type ="text/javascript">
        //创建一个XMLHttpRequest对象
        var xmlHttp = createXMLHttpRequest();
        if(xmlHttp)
        {
            //true代表异步请求
            xmlHttp.open("GET","Data.xml",true);
            //回调函数
            xmlHttp.onreadystatechange = function()
            {
                //0,未初始化;1,正在加载;2,加载完成;3,交互;4,完成
                if(xmlHttp.readyState == 4)
                {
                    var myPanel = document.getElementById("myPanel");
                    var doc = xmlHttp.responseXML;
                    var node = doc.selectSingleNode("//Customers/Customer/Lastname/text()");
                    myPanel.innerHTML = node.nodeValue;
                }
            }
            //发送请求,因为使用的是GET方法,所以不需要传送参数
            xmlHttp.send(null);
        }
    </script>

    XML文档:
    <?xml version="1.0" encoding="utf-8"?>
    <Customers>
          <Customer>
                <Firstname>Joe</Firstname>
                <Lastname>Bloggs</Lastname>
                <email>joe@bloggs.com</email>
          </Customer>
          <Customer>
                <Firstname>Alan</Firstname>
                <Lastname>Anonymous</Lastname>
                <email>anon@ymous.com</email>
          </Customer>
          <Customer>
                <Firstname>Marvin</Firstname>
                <Lastname>Martian</Lastname>
                <email>marvin@mars.com</email>
          </Customer>
    </Customers>
----------------------------------------------------------------------------------------------------
0035:
    处理异步请求的综合例子:
    <head>
        <script type ="text/javascript">
            //创建一个XMLHttpRequest对象
            var xmlHttp = createXMLHttpRequest();
            function loadCustomers()
            {
                if(xmlHttp)
                {
                    xmlHttp.open("GET","Data.xml",false);
                    xmlHttp.send(null);
                }
                if(xmlHttp.status == 200)
                {
                    var xmlDoc = xmlHttp.responseXML;
                    var nodes = xmlDoc.selectNodes("//Customers/Customer/Lastname/text()");
                    var mySelect = document.getElementById("mySelect");
                    for(var i = 0;i < nodes.length;i++)
                    {
                        var lastName = nodes[i].nodeValue;
                        var htmlCode = document.createElement("option");
                        mySelect.options.add(htmlCode);
                        htmlCode.text = lastName;
                        htmlCode.value = lastName;
                    }
                }
            }
        </script>
    </head>
    <body onload = "javascript:loadCustomers();">
        <form id = "myForm" runat ="server">     
            <select id = "mySelect" onchange ="javascript:displayDetail();">
                <option value="">- 选择一个客户 -</option>
            </select>
            <div id = "myPanel">
                <p>详细:</p>
                <span id = "mySpan"></span>
            </div>
        </form>
       
        <script type ="text/javascript">
            function displayDetail()
            {
                if(xmlHttp)
                {
                    //true代表异步请求
                    xmlHttp.open("GET","Data.xml",true);
                    //回调函数
                    xmlHttp.onreadystatechange = function()
                    {
                        //0,未初始化;1,正在加载;2,加载完成;3,交互;4,完成
                        if(xmlHttp.readyState == 4)
                        {
                            var mySelect = document.getElementById("mySelect");
                            var doc = xmlHttp.responseXML;
                            var lastName = mySelect.options[mySelect.selectedIndex].value;
                            var node = doc.selectSingleNode("//Customers/Customer[Lastname='" +lastName+ "']");
                            var detail = node.selectSingleNode('Firstname/text()').nodeValue + "<br>";
                            detail = detail + node.selectSingleNode('email/text()').nodeValue;
                            var mySpan = document.getElementById("mySpan");
                            mySpan.innerHTML = detail;
                        }
                    }
                    //发送请求,因为使用的是GET方法,所以不需要传送参数
                    xmlHttp.send(null);
                }
            }
        </script>
    </body>
----------------------------------------------------------------------------------------------------
0036:
    XMLHttpRequest常用属性和方法:
    ●abort():取消当前请求。
    ●getAllResponseHeaders():返回所有HTTP头。
    ●getResponseHeader("headername"):返回具体的HTTP头部分。
    ●open("method","URL","async","uname","pswd"):method参数可以有三种GET、POST和PUT。只返回数据或用
URL传送小于512字节数据时使用。POST在发送大于512字节数据时使用。
    ●send(content):发送请求。
    ●setRequestHeader("label","value"):设置HTTP发送头部分。

    ●onreadystatechange:事件回调函数指针。
    ●readyState:请求的处理情况。0未初始化;1正在加载;2加载完成;3交互;4完成。
    ●responseText:将返回的数据看做字符串。
    ●responseXML:将返回的数据看做XML。
    ●status:请求返回的状态。404Not Found;200OK;500Server Error。
    ●statusText:状态的文本。
----------------------------------------------------------------------------------------------------
0037:
    服务器端处理Ajax请求的例子:
    客户端代码:
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        xmlHttp.open("GET","http://localhost/TestSite/Default.aspx?arg=123",true);
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readystate == 4 && xmlHttp.status == 200)
            {
                document.write(xmlHttp.responseText);
            }
        }
        xmlHttp.send(null);
    }
    服务器端代码:
    protected void Page_Load(object sender, EventArgs e)
    {     
        if (this.Request.QueryString.Count > 0)
        {
            string arg = this.Request.QueryString["arg"];
            this.Server.Transfer("Data.xml");
        }
    }
----------------------------------------------------------------------------------------------------
0038:
    IHttpHandler的实现:
    客户端代码:
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        xmlHttp.open("GET","http://localhost/TestSite/MyHandler.ashx?arg=123",true);
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readystate == 4 && xmlHttp.status == 200)
            {
                document.write(xmlHttp.responseText);
            }
        }
        xmlHttp.send(null);
    }
    服务器代码:“添加新项”-“一般处理程序”
    <%@ WebHandler Language="C#" Class="MyHandler" %>

    using System;
    using System.Web;

    public class MyHandler : IHttpHandler
    { 
        public void ProcessRequest (HttpContext context)
        {
            string str = context.Request.QueryString["arg"];
            string xmlData = @"<?xml version=""1.0"" encoding=""utf-8""?><root><name>小李</name></root>";
            context.Response.ContentType = "application/xml";
            context.Response.Write(xmlData);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
----------------------------------------------------------------------------------------------------
0039:
    IHttpHandler处理POST方法过来的数据:
    客户端代码:
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        xmlHttp.open("POST","http://localhost/TestSite/MyHandler.ashx",true);
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readystate == 4 && xmlHttp.status == 200)
            {
                document.write(xmlHttp.responseText);
            }
        }
        xmlHttp.send("arg=123");
    }
    服务器端代码:
    <%@ WebHandler Language="C#" Class="MyHandler" %>

    using System;
    using System.Web;

    public class MyHandler : IHttpHandler
    { 
        public void ProcessRequest (HttpContext context)
        {
            byte[] data = new byte[context.Request.ContentLength];
            context.Request.InputStream.Read(data,0,context.Request.ContentLength);
            string str = System.Text.UTF8Encoding.UTF8.GetString(data);
            string xmlData = @"<?xml version=""1.0"" encoding=""utf-8""?><root><name>" + str + "</name></root>";
            context.Response.ContentType = "application/xml";
            context.Response.Write(xmlData);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
----------------------------------------------------------------------------------------------------
0040:
    Web Service处理Ajax请求的例子:
    客户端代码:
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        xmlHttp.open("POST","http://localhost/TestSite/WebService.asmx/HelloWorld",true);
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readystate == 4 && xmlHttp.status == 200)
            {
                document.write(xmlHttp.responseText);
            }
        }
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttp.send("str=hello");//参数必须以键值对的方式传送,这个参数名必须与Web服务方法中的参数名一样
    }
    服务器端代码:
    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class WebService : System.Web.Services.WebService
    {

        public WebService ()
        {

        }
        [WebMethod]
        public string HelloWorld(string str)
        {
            return str;
        }
       
    }
----------------------------------------------------------------------------------------------------
0041:
   XML是区分大小写的。
----------------------------------------------------------------------------------------------------
0042:
    返回DataTable的情况:
    客户端:
    var xmlHttp = createXMLHttpRequest();
    if(xmlHttp)
    {
        xmlHttp.open("GET","http://localhost/TestSite/WebService.asmx/GetDataSet",true);
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readystate == 4 && xmlHttp.status == 200)
            {             
                var strObj = xmlHttp.responseText;
                alert(strObj);
            }
        }
        xmlHttp.send("null=null");//必须带有这个参数,暂时不明白为什么?(这个Web服务本身不需要参数的)
    }
----------------------------------------------------------------------------------------------------
0043:
    ASP.NET 2.0中的TreeView、GridView和DetailsView几个控件都支持异步请求。直接设置EnableClientScript
属性为true就可以了。
----------------------------------------------------------------------------------------------------
0044:
    判断浏览器是否支持回调脚本:
    this.Request.Browser.SupportsCallback;
    this.Request.Browser.SupportsXmlHttp;
----------------------------------------------------------------------------------------------------
0045:
    ICallbackEventHandler接口:这个接口可以用来实现page或者control的异步处理能力。通过实现这个接口,
page或者control可以生成客户端JavaScript脚本。这个接口包含两个主要的方法:
    ●string GetCallbackResult();
    ●void RaiseCallbackEvent(string eventArgument);
----------------------------------------------------------------------------------------------------
0046:
    注册客户端脚本的方法:
    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowMessage", "alert('你好');", true);
----------------------------------------------------------------------------------------------------
0047:
    获得异步请求客户端脚本的引用:
    string js = Page.ClientScript.GetCallbackEventReference(this.GridView1,"arg","OnServerCallComplete","ctx",true);
    this.Response.Write(js);
----------------------------------------------------------------------------------------------------
0048:
    使用ASP.NET内置的异步请求机制:
    客户端代码:
    <body>
        <form id="form1" runat="server">
            <input id="Button1" type="button" value="button" onclick="startAsyncCall('myArg','myCtx')"/>
        </form>
        <script type="text/javascript">
         function OnServerCallComplete(arg,ctx)
         {
            //客户端调用服务器端方法返回数据的处理过程,arg为返回的数据,类型是string
            document.write("异步请求完成" + "<br>");
            document.write(arg + "<br>");
            document.write(ctx + "<br>");
         }
        </script>
    </body>
    服务器端代码:
    public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string js = Page.ClientScript.GetCallbackEventReference(this,"arg","OnServerCallComplete","ctx",true);
            string startAsyncCall = @"
            function startAsyncCall(arg,ctx)
            {
                " + js + @"
            }";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "startAsyncCall", startAsyncCall,true);
        }
        public string GetCallbackResult()
        {
            //将RaiseCallbackEvent中获取的数据返回给调用的客户端
            return "Server method completed at:" + DateTime.Now.ToLongTimeString();
        }
        public void RaiseCallbackEvent(string eventArgument)
        {
            //复杂的获取数据的运算
            System.Threading.Thread.Sleep(5000);
        }
    }
----------------------------------------------------------------------------------------------------
0049:
    Ajax.NET Pro框架的使用:
    ●添加AjaxPro.dll引用。
    ●在Web.Config文件中添加配置节点:
    <system.web>
      <httpHandlers>
        <add verb="POST,GET" path="AjaxPro/*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro"/>
      </httpHandlers>
    </system.web>
    ●将page注册为AjaxPro支持的page:
    protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(this.GetType());
    }
    ●将服务端方法注册为AjaxPro支持的方法:
    [AjaxPro.AjaxMethod()]
    public string Show(string str)
    {
        return str + System.DateTime.Now.ToLongTimeString();
    }
    ●客户端代码:
    <form id="form1" runat="server">
        <input id="Button1" type="button" value="button" onclick="javascript:clickHandler();"/>
    </form>
    <script type="text/javascript">
     function clickHandler()
     {
        var obj = _Default.Show("时间是:");
        var strTime = obj.value;
        document.write(strTime);
     }
    </script>
----------------------------------------------------------------------------------------------------
0050:
    使用Ajax.NET Pro框架返回一个DataGrid的HTML代码
    服务器端代码:
    [AjaxPro.AjaxMethod()]
    public string ShowDataGrid()
    {
        SqlConnection aSqlConnection = new SqlConnection(@"Server=smartkernel-PC\SQLSERVER2000;DataBase=pubs;uid=sa;pwd=sa");
        SqlCommand aSqlCommand = aSqlConnection.CreateCommand();
        aSqlCommand.CommandText = @"SELECT * FROM [employee]";
        SqlDataAdapter aSqlDataAdapter = new SqlDataAdapter();
        aSqlDataAdapter.SelectCommand = aSqlCommand;
        DataTable aDataTable = new DataTable();
        aSqlDataAdapter.Fill(aDataTable);
        DataGrid aDataGrid = new DataGrid();
        aDataGrid.DataSource = aDataTable;
        aDataGrid.DataBind();
        return GetHtml(aDataGrid);
    }
    //获得控件输出的HTML字符串
    public string GetHtml(Control control)
    {
        System.IO.MemoryStream aMemoryStream = new System.IO.MemoryStream();
        System.IO.StreamWriter sw = new System.IO.StreamWriter(aMemoryStream);
        System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
        control.RenderControl(htw);
        byte[] abyte = aMemoryStream.ToArray();
        return System.Text.Encoding.Default.GetString(abyte);
    }
    客户端代码:
    <form id="form1" runat="server">
        <div id = "myDiv"></div>
        <input id="Button1" type="button" value="button" onclick="javascript:clickHandler();"/>
    </form>
    <script type="text/javascript">
     function clickHandler()
     {
        var obj = _Default.ShowDataGrid();
        var myDiv = document.getElementById("myDiv");
        myDiv.innerHTML = obj.value;;
     }
    </script>
----------------------------------------------------------------------------------------------------
0051:
    AjaxPro框架直接处理DataTable数据类型
    服务器端代码:
    [AjaxPro.AjaxMethod()]
    public DataTable ShowDataTable()
    {
        SqlConnection aSqlConnection = new SqlConnection(@"Server=smartkernel-PC\SQLSERVER2000;DataBase=pubs;uid=sa;pwd=sa");
        SqlCommand aSqlCommand = aSqlConnection.CreateCommand();
        aSqlCommand.CommandText = @"SELECT * FROM [employee]";
        SqlDataAdapter aSqlDataAdapter = new SqlDataAdapter();
        aSqlDataAdapter.SelectCommand = aSqlCommand;
        DataTable aDataTable = new DataTable();
        aSqlDataAdapter.Fill(aDataTable);
        return aDataTable;
    }
    客户端代码:
    <form id="form1" runat="server">
        <div id = "myDiv"></div>
        <input id="Button1" type="button" value="button" onclick="javascript:clickHandler();"/>
    </form>
    <script type="text/javascript">
     function clickHandler()
     {
        var obj = _Default.ShowDataTable();
        if(obj.value != null && obj.value.Rows.length > 0)
        {
            var dataTable = obj.value;
            var table = new Array();
            table[table.length] = '<table border=1>';
            for(var i = 0;i < dataTable.Rows.length;i++)
            {
                var row = dataTable.Rows[i];
                table[table.length] = '<tr>';
                //row暂时不支持索引,不知道为什么?
                table[table.length] = '<td valign=top>' + row["fname"] + '</td>';
                table[table.length] = '<td valign=top>' + row["lname"] + '</td>';
                table[table.length] = '<td valign=top>' + row["hire_date"] + '</td>';
               
                table[table.length] = '</tr>';
            }
            table[table.length] = '</table>';
            var myDiv = document.getElementById("myDiv");
            myDiv.innerHTML = table.join('');
        }
     }
    </script>
----------------------------------------------------------------------------------------------------
0052:
    上面的AjaxPro框架的用法全是同步的,下面介绍异步的方法:
    服务器端:
    [AjaxPro.AjaxMethod()]
    public string DoSomething(string str)
    {
        System.Threading.Thread.Sleep(5000);
        return str + DateTime.Now.ToLongTimeString();
    }
    客户端:
    <form id="form1" runat="server">
        <div id = "myDiv"></div>
        <input id="Button1" type="button" value="button" onclick="javascript:clickHandler();"/>
    </form>
    <script type="text/javascript">
     function clickHandler()
     {
        var obj = _Default.DoSomething("时间是:",callbackHandler);
     }
     //回调函数
     function callbackHandler(response)
     {
        document.write(response.value);
     }
    </script>
----------------------------------------------------------------------------------------------------
0053:
    AjaxPro框架问题:如果想传递自己定义的类型,可以将类型标志化为可串行化或者实现自己的转换器。
----------------------------------------------------------------------------------------------------
0054:
    MagicAjax框架的使用:
    ●添加dll引用。
    ●Web.Config中添加节点:
    <system.web>
      <pages>
        <controls>
          <add namespace="MagicAjax.UI.Controls" assembly="MagicAjax" tagPrefix="ajax"/>
        </controls>
      </pages>
      <httpModules>
        <add name="MagicAjaxModule" type="MagicAjax.MagicAjaxModule,MagicAjax"/>
      </httpModules>
    </system.web>
    ●工具箱添加控件。
    ●拖放一个AjaxPanel控件。
    ●所有在AjaxPanel中的控件,自动实现无刷新请求。后台代码的写法和以前一样,并且控件都是服务器控件。
----------------------------------------------------------------------------------------------------
0055:
    MagicAjax会在延迟处理的页面右上角自动加一个Loading提示。
---------------------------------------------------------------------------------------------------- 

posted @ 2008-04-12 09:55  彷徨......  阅读(526)  评论(0编辑  收藏  举报