前台页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="username.aspx.cs" Inherits="username" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/Jquery1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#txtname').blur(function () {
vailtname();
})
function vailtname() {
//验证用户名不能为空
var mytext = $('#txtname').val();
if (mytext == '') {
$('#txtname').next().text('用户名不能为空').css('color', 'red');
return false;
}
else {
WebService.vilatename(mytext, onSuccess1, onFailed1);
}
}
function onSuccess1(result) {
if (result == true) {
$('span').text('');
var img = "<img src=images/kws_safe.gif/>";
$('span').append(img);
return true;
}
else {
$('span').text('用户名已存在').css('color', 'red');
return false;
}
}
function onFailed1() {
alert('方法调用失败');
}
$('#btnOk').bind("click", function () {
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService.asmx"/>
</Services>
</asp:ScriptManager>
<div>
<input id="txtname" type="text" />
<span></span><br />
<input id="btnOk" type="button" value="确定" />
</div>
</form>
</body>
</html>
后台:WebService1.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
private string sqlcnn = ConfigurationManager.ConnectionStrings["sqlcnn"].ConnectionString;
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public bool vilatename(string name)
{
object getvalue = null;
using (SqlConnection con = new SqlConnection(sqlcnn))
{
using (SqlCommand com = con.CreateCommand())
{
com.CommandText = "select UserName from UserInfo where UserName=@name";
com.Parameters.AddWithValue("@name",name);
con.Open();
getvalue = com.ExecuteScalar();
}
}
if (getvalue != null)
{
return false;
}
else
{
return true;
}
}
}