白桦的天空

第一次的心动,永远的心痛!
  首页  :: 新随笔  :: 联系 :: 管理

Ajax.net Onloading Example

Posted on 2007-11-14 09:57  白桦的天空  阅读(170)  评论(0)    收藏  举报
一直想使用Ajax技术,可总是没有时间。最近由于新网站需要用到Ajax技术,所以下载学习了一下。由于使用的是.net1.1sp1,所以Atlas是没法用了,以下文字仅针对AjaxPro。AjaxPro.dll可以在http://www.ajaxpro.info/下载,该网站也提供了详细的教程和实例供下载。
1.首先下载AjaxPro( latest version 6.10.6.1.),压缩包中提供了asp.net2.0和1.1的版本,以及web.config配置文件模板;
2.在项目中引用AjaxPro.Dll(For asp.net 1.1版本的);
3.配置web.config文件,在<configuration>中<system.web>外,添加以下文字:
<!-- Handler configuration for Ajax.NET Professional -->
    
    
<location path="ajaxpro">
        
<system.web>
            
<httpHandlers>
                
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro"/>
            
</httpHandlers>
        
</system.web>
    
</location>

4.添加Web窗体,如:LoadingDemo.aspx(参考:http://www.ajaxpro.info/Examples/Special/onloading.aspx
源码如下:
<%@ Page language="c#" ClassName="LoadingDemo" Inherits="System.Web.UI.Page" %>
<script runat="server" language="c#">

private 
void Page_Load(object sender, EventArgs e)
{
    AjaxPro.Utility.RegisterTypeForAjax(
typeof(LoadingDemo));
}

[AjaxPro.AjaxMethod]
public DateTime LongOperation()
{
    System.Threading.Thread.Sleep(
2000);
    
return DateTime.Now;
}


</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html>
  
<head>
    
<title>Ajax.NET - OnLoading Example</title>
    
<link rel="stylesheet" type="text/css" href="http://www.cnblogs.com/css/main.css"/>
    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  
</head>
  
<body>
 
<form id="Form1" method="post" runat="server"></form>

<div class="content">

<h1>OnLoading Examples</h1>

<p>Click <href="javascript:doTest1();void(0);">here</a>
 to start a long operating method (2 seconds). After you have clicked on the link you should see a
 
<i>Loading...</i> message in the upper left corner.</p>

</div>

<div id="loadinfo"
 style
="visibility:hidden;position:absolute;left:0px;top:0px;background-color:Red;color:White;">
Loading...</div>

<class="footer">Last updated: November 2, 2005 by
 
<href="http://weblogs.asp.net/mschwarz/contact.aspx" target="_blank">Michael Schwarz</a></p>
<p><href="http://validator.w3.org/check?uri=referer">
<
img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Transitional"
 height
="31" width="88" /></a></p>

<script type="text/javascript" defer="defer">

AjaxPro.onLoading 
= function(b) {
    
var l = document.getElementById("loadinfo");
    l.style.visibility 
= b ? "visible" : "hidden";
}

function doTest1() {
    ASP.LoadingDemo.LongOperation(doTest1_callback);
}

function doTest1_callback(res) {
    alert(res.value);
}

</script>
  
</body>
</html>
5.注意事项:
a.在作者的先前一个版本中(参考http://www.schwarz-interactive.de/Examples/Special/onloading.aspx
<script type="text/javascript" defer="defer">

AjaxPro.onLoading 
= function(b) {
......
这里是下面这样的:
<script type="text/javascript" defer="defer">

ASP.LoadingDemo.onLoading 
= function(b) {
......

测试结果是第一种可行,第二种写法不会显示loading的字样,不知道是不是因为Ajax的版本问题。

b.作者没有使用cs文件,所以需要注意的是,这时名字空间为ASP,即:
ASP.LoadingDemo.LongOperation(doTest1_callback);
如果使用cs文件,那么上面一行要相应改成自己的名字空间,比如:
LoadingDemo.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace PhantomPro.AjaxProject
{
    
/// <summary>
    
/// LoadingDemo 的摘要说明。
    
/// </summary>
    public class LoadingDemo : System.Web.UI.Page
    {
        
private void Page_Load(object sender, System.EventArgs e)
        {
            
// 在此处放置用户代码以初始化页面
            AjaxPro.Utility.RegisterTypeForAjax(typeof(LoadingDemo));
        }

        
#region Web 窗体设计器生成的代码
        
override protected void OnInit(EventArgs e)
        {
            
//
            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base.OnInit(e);
        }
        
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {    
            
this.Load += new System.EventHandler(this.Page_Load);
        }
        
#endregion
        [AjaxPro.AjaxMethod]
        
public DateTime LongOperation()
        {
            System.Threading.Thread.Sleep(
2000);//延时2秒,方便查看Loading效果
            return DateTime.Now;
        }
    }
}
LoadingDemo.aspx:
<%@ Page language="c#" Codebehind="LoadingDemo.aspx.cs" AutoEventWireup="false"
 Inherits
="PhantomPro.AjaxProject.LoadingDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<HTML>
    
<HEAD>
        
<title>Ajax.NET - OnLoading Example</title>
        
        
<link rel="stylesheet" type="text/css" href="http://www.cnblogs.com/css/main.css">
        
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
</HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
        
</form>
        
<div class="content">
            
<h1>OnLoading Examples</h1>
            
<p>Click <href="javascript:doTest1();void(0);">here</a> to start a long operating 
                method (2 seconds). After you have clicked on the link you should see a 
<i>Loading</i>
                message in the upper left corner.
</p>
        
</div>
        
<div id="loadinfo"
 style
="LEFT:0px;VISIBILITY:hidden;COLOR:white;POSITION:absolute;TOP:0px;BACKGROUND-COLOR:red">
Loading...</div>
        
<class="footer">Last updated: November 2, 2005 by
 
<href="http://weblogs.asp.net/mschwarz/contact.aspx" target="_blank">
                Michael Schwarz
</a></p>
        
<p><href="http://validator.w3.org/check?uri=referer">
<
img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Transitional" height="31"
                    width
="88"></a></p>
        
<script type="text/javascript" defer>

AjaxPro.onLoading 
= function(b) {
    
var l = document.getElementById("loadinfo");
    l.style.visibility 
= b ? "visible" : "hidden";
}

function doTest1() {
    PhantomPro.AjaxProject.LoadingDemo.LongOperation(doTest1_callback);//这里换成自己的名字空间
}

function doTest1_callback(res) {
    alert(res.value);
}

        
</script>
    
</body>
</HTML>
6.顺便测试一下DataSet的效果:
AjaxDemo.aspx.cs:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Data.SqlClient;

namespace PhantomPro.AjaxProject
{
    
/// <summary>
    
/// AjaxDemo 的摘要说明。
    
/// </summary>
    public class AjaxDemo : System.Web.UI.Page
    {
        
private void Page_Load(object sender, System.EventArgs e)
        {
            
// 在此处放置用户代码以初始化页面
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PhantomPro.AjaxProject.AjaxDemo));
        }

        
#region Web 窗体设计器生成的代码
        
override protected void OnInit(EventArgs e)
        {
            
//
            
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            
//
            InitializeComponent();
            
base.OnInit(e);
        }
        
        
/// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>
        private void InitializeComponent()
        {    
            
this.Load += new System.EventHandler(this.Page_Load);

        }
        
#endregion
        
        
        [AjaxPro.AjaxMethod]
        
public string GetTable(string str)
        {
            System.Threading.Thread.Sleep(
2000);  //进程睡眠(延时)2秒
            string s="";
            DataSet ds
=new DataSet();
            
try
            {
                SqlConnection conn
=new SqlConnection(ConfigurationSettings.AppSettings["DbString"]);
                
string strSql="select * from Employees where EmployeeID="+str;
                conn.Open();
                SqlDataAdapter ap
=new SqlDataAdapter(strSql,conn);
                ap.Fill(ds,
"table1");
                conn.Close();
            
                
if(ds.Tables["table1"].Rows.Count>0)
                {
                    DataGrid dg 
= new DataGrid();

                   dg.DataSource
=ds.Tables["table1"].DefaultView;
                   dg.DataBind();
                    
//以下是网站摘录的

                    
//实例化一个HtmlTextWriter的类
                    System.Text.StringBuilder strb = new System.Text.StringBuilder();
                    System.IO.StringWriter sw 
= new System.IO.StringWriter( strb );
                    System.Web.UI.HtmlTextWriter htw 
= new HtmlTextWriter( sw );

                    
//执行控件的render并输出到HtmlTextWriter里
                    dg.RenderControl( htw );

                    s 
= strb.ToString();
                }
                
else
                {
                    s
="没有相关数据!";
                }
                
            }
            
catch
            {
                s
="error!!";
            }
           

        

            
return s;//最后就是返回这个html啦
        }
    }
}
AjaxDemo.aspx:
<%@ Page language="c#" Codebehind="AjaxDemo.aspx.cs" AutoEventWireup="false"
 Inherits
="PhantomPro.AjaxProject.AjaxDemo" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>AjaxDemo</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
            
<div id="div1">
                
<span id="span1">A DEMO of AjaxPro</span>
                
<div id="div2">
                    Employee ID: 
<INPUT id="TextBox3" type="text">&nbsp;
                    
<br><href="javascript:getTable();">test</a>
                
</div>
                
<div id="save_ing" style="visibility:hidden;"><img src="uploading.gif">请等待</div>
                
<div id="div3" style="visibility:hidden;"></div>
            
</div>
            
        
<script type="text/javascript">
        AjaxPro.onLoading 
= function(b) {
    
var l = document.getElementById("save_ing");   
    l.style.visibility 
= b ? "visible" : "hidden";
    document.getElementById(
"div3").style.visibility=b?"hidden" : "visible";
    
  }
        
   
function getTable()
    {
 PhantomPro.AjaxProject.AjaxDemo.GetTable(document.getElementById(
"TextBox3").value,getTable_callback);
    }
   
function getTable_callback(res)
    {
        
var p=res.value;
        
var d3=document.getElementById("div3");
        
        d3.innerHTML
=p;
        
    }
        
        
        
        
</script>
        
</form>
    
</body>
</HTML>
需要注意的是,如果按下面的方式:
......
        
function getTable()
{
var p=document.getElementById("div3");
var t=
document.getElementById("TextBox3");
p.innerHTML=PhantomPro.AjaxProject.AjaxDemo.GetTable(t.value).value;
}

        
</script>
......
可以显示结果,不过不能显示Loading效果。
7.初次体验Ajax,有些不太适应,尤其的是调试的阶段。传统的方式可以得到具体的错误消息,比如Sql连接错误等,Ajax得到的是js错误代码,很难判断是哪里错了。曾经花费很长时间调试DataSet,结果发现是Sql密码写错了,呵呵。也可能有调试的办法,自己还不知道吧。还有一些代码的实例,方法基本一样,不再记录了。总得来说,虽然花费了一整天的时间调试,不过最终Ajax的效果是令人兴奋的。