asp.net2.0 使用ajaxpro实现ajax效果
一直想学习ajax的技术,微软有asp.net ajax技术,使用起来也挺简单,这里,我使用另外一种ajaxpro组件来实现,
使用ajax好处就是可以实现页面的无刷新,然后向服务器提交的数据量更小,同时所花费的时间更少,因为好多在服务器端
做的事,现在让它在客户端来做了,当然就减轻了服务器的负担.下面就介绍下我这个demo吧
step 1.
到ajaxpro的官方网站www.ajaxpro.info 下载ajaxpro组件
step 2.
新建一个项目learnmore,添加引用,将刚才下载的ajaxpro.2添加进来,同时在web.config的 <system.web> </system.web>中如下配置:
<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
step 3.
新建一个类GetDataFromDB.cs,里面写一个方法getdata(string userID)
[AjaxPro.AjaxMethod]//表明这个方法是异步的,我这里做的只是通过用户的ID把用户名字取出来
public static string getdata(string userID)
{
string userName = "";
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("server=.;Database=test;uid=sa;pwd=sa");
con.Open();
SqlCommand cmd = new SqlCommand("select username from tb_users where userID='"+userID+"'", con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
userName = sdr[0].ToString();
}
con.Close();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
return userName;
}
step 4.
在webForm1.aspx的Page_load事件里注册上面那个类
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(LearnMore.GetDataFromDB));
}
step 5.
新建一个页面WebForm1.aspx,放置两个html的控件text,和一个button,给button的onclick添加一个事件
<input id="Button1" type="button" value="button" onclick="return Button1_onclick()" />
function Button1_onclick()
{
var userName=LearnMore.GetDataFromDB.getdata(document.form1.textUserID.value);//客户端调用服务器端脚本
document.form1.textUserName.value=userName.value;
}
step 6.
protected void Application_Start(object sender, EventArgs e)
{
AjaxPro.Utility.HandlerPath = "ajaxPro";
}
-----------------------------------------------------------------------------
请注意,Ajax.net实际有AjaxPro.dll和Ajax.dll两个版本,这两个版本使用上虽然差不多,但还是有区别的,主要的区别在下面两点
(1)web.config配置文件不一样
Ajax.dll的配置文件写法为
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
AjaxPro.dll的配置文件写法为
<add verb="*" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro"/>
(2)调用服务器方法的时候方式不一样,有很多朋友就是因为这个原因,发现命名空间找不到或者对象未定义
引用Ajax.dll的时候,调用服务器方法不要加命名空间,
应用AjaxPro.dll的时候,调用服务器方法需要加命名空间
例如当页面设置为这种设置的时候
<%@ Page language="c#" Codebehind="Test.aspx.cs" AutoEventWireup="false" Inherits="Web.Test" %>
客户端调用方式
Ajax.dll为
var response=Test.GetServerMethod();
alert(response.value);
AjaxPro.dll为
var response=Web.Test.GetServerMethod();
alert(response.value);
另外AjaxPro官方最新测试版本,在生成客户端脚本的时候会出现空指针错误,所以请大家不要试用这种版本,尽量试用稳定版本
浙公网安备 33010602011771号