这里用到ASP中的WebService与实现界面的数据交换!
实现无刷新验证用户名是否存在
WebService页面代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
namespace AJAX
{
///<summary>
/// VerifyUserName 的Ì?摘a要°a说¦Ì明¡Â
///</summary>
[WebService(Namespace= "http://tempuri.org/")]
[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若¨?要°a允¨º许¨ª使º1用®? ASP.NET AJAX 从䨮脚?本À?中D调Ì¡Â用®?此ä? Web 服¤t务?,ê?请?取¨?消?对?下?行D的Ì?注Á¡é释º¨ª。¡ê
[System.Web.Script.Services.ScriptService]
public class VerifyUserName: System.Web.Services.WebService
{
stringstr = System.Configuration.ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
[WebMethod]
public string HelloWorld()
{
return"Hello World";
}
[WebMethod]
public string GetUser(stringusername)
{
SqlConnectionsqlCnn = new SqlConnection(str);
SqlCommandsqlCmm = new SqlCommand("select count(*) from UserInfo whereUserName=@username", sqlCnn);
sqlCmm.Parameters.AddWithValue("@username",username);
sqlCnn.Open();
objectobj = sqlCmm.ExecuteScalar();
sqlCmm.Dispose();
sqlCnn.Dispose();
returnobj.ToString();
}
}
}
实现页面html代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>验¨¦证¡è用®?户¡ì名?是º?否¤?存ä?在¨²</title>
<script src="Jquery1.7.js" type="text/javascript"></script>
<style type="text/css">
.color{border:2px solid Red;}
</style>
<script type="text/javascript">
$(function() {
$('#txtUserName').focus(function () {
$(this).addClass('color');
$(this).val('');
})
$('#txtUserName').blur(function () {
$(this).removeClass('color');
if($(this).val() != ""){
AJAX.VerifyUserName.GetUser($(this).val().toString(),onSuccess, onFailed);
}
})
functiononSuccess(e) {
if(parseInt(e) > 0) {
$('span').text('改?用®?户¡ì名?已°?注Á¡é册¨¢!ê?').css('color', 'Red');
}
else{
$('span').text('改?用®?户¡ì名?可¨¦以°?使º1用®?!ê?').css('color', 'Green');
}
}
functiononFailed() {
alert('GameOver!');
}
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/VerifyUserName.asmx" />
</Services>
</asp:ScriptManager>
<div>
用户名?:<input id="txtUserName" type="text" value="请输入用户名"/> <span></span>
</div>
</form>
</body>
</html>