最近有时间就自己尝试做了个用Ajax检测用户输入用户名时自动检测输入的用户名是否被注册的登陆功能,并带有进度提示,用到了Web Service,客户端调用服务器端的函数的方法。
Login.aspx页面:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="CheckUserNameService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr>
<th colspan="2">
Login Field</th>
</tr>
<tr>
<td>
UserName:</td>
<td>
<input type="text" name="UserName" id="UserName" οnblur="CheckName()" style="width: 150px" /><span id="resultMessage"></span>
</td>
</tr>
<tr><td>Password:</td><td>
<asp:TextBox ID="txtPassword" TextMode="password" runat="server" Width="150px"></asp:TextBox></td></tr>
<tr><td colspan="2">
<asp:Button ID="Button1" runat="server" Text="Login" /></td></tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function CheckName()
{
document.getElementById("resultMessage").style.color="black";
document.getElementById("resultMessage").innerText="Checking Name,please wait...."; //进度提示
var ServerRequest=CheckUserNameService.CheckUserName(document.getElementById("UserName").value,onComplete)
}
function onComplete(result) //根据返回值判断来输出不同的值
{
if(result=="1"){
document.getElementById("resultMessage").style.color="red";
document.getElementById("resultMessage").innerText="This Name has been used.";
}
if(result=="0"){
document.getElementById("resultMessage").style.color="green";
document.getElementById("resultMessage").innerText="This Name you can use.";
}
}
</script>
</div>
</form>
CheckUserNameService.asmx页面:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.OleDb;
using System.Web.Script.Services;
/// <summary>
/// CheckUserNameService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService] //必须的
public class CheckUserNameService : System.Web.Services.WebService {
public CheckUserNameService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string CheckUserName(string strName) {
System.Threading.Thread.Sleep(3000);
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.jet.oledb.4.0; data source=" + Server.MapPath("App_Data/Data.mdb"));
string sql = "select [ID] from Admin where UserName= " + strName.ToString() + " ";
OleDbCommand cmd = new OleDbCommand(sql, cn);
OleDbDataReader dr;
try
{
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
return "1";
}
else
{
return "0";
}
dr.Close();
}
catch (OleDbException oe)
{
return "Someting wrong.";
}
finally
{
cn.Close();
}
}
}