asp.net JQuery Ajax 结合 WebService 自动匹配 用户是否存在验证

创建WebService

GetAuto.asmx的cs写入方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using Model;
using DBUtility;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
///GetAuto 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
 [System.Web.Script.Services.ScriptService]
public class GetAuto : System.Web.Services.WebService {

    public GetAuto () {

        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }
    [WebMethod]
    public bool VerifyCustomers(string sUserName)
    {
        int customers = 0;
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select count(*) as vc  from [table] where " +
                "姓名 ='" + sUserName + "'";
                //cmd.Parameters.AddWithValue("@code", code);
                //cmd.Parameters.AddWithValue("@name", name);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers=Convert.ToInt32(sdr["vc"]);
                    }
                }
                conn.Close();
            }
            return customers>0?false:true;
        }
    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string[] GetCustomers(string prefix)
    {
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                string stra = prefix.Replace(",", ",").Trim();
                string name="", code = "";
                if (stra.Contains(","))
                {
                    int IndexofA = stra.IndexOf(",");
                    int IndexofAll = stra.Length;
                    code = stra.Substring(0, IndexofA).Trim();
                    name = stra.Substring(IndexofA + 1, IndexofAll - IndexofA - 1).Trim();
                }
                else
                {
                    code = prefix;
                }
                cmd.CommandText = "select ISNULL([姓名],'') as name,员工编号 as code  from [table] where " +
                "员工编号 like '%" + code + "%'";
                if (!string.IsNullOrEmpty(name)) cmd.CommandText += " and [姓名] like '%" + name + "%'";
                //cmd.Parameters.AddWithValue("@code", code);
                //cmd.Parameters.AddWithValue("@name", name);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(string.Format("{0}-{1}", sdr["name"], sdr["code"]));
                    }
                }
                conn.Close();
            }
            return customers.ToArray();
        }
    }
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    
}

aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqAutocomplete.aspx.cs" Inherits="Test_JqAutocomplete" %>

<!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="../JQuery/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="../JQuery/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>
    <link href="jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" />
   
<script type="text/javascript">
    
    $(document).ready(function () {
        $("#<%=txtSearch.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Test/GetAuto.asmx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item,
                                txt: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerId.ClientID %>").text(i.item.val);
                $("#<%=Label1.ClientID %>").text(i.item.txt);
            },
            minLength: 1
        });
    });
</script>
<script type="text/javascript">
    $(function () {
        //获得焦点focus//失去焦点blur
        $("#txtUserName").blur(function (e) {
            e.preventDefault();

            // 首先判断用户名是否为空,并给出提示
            if ($("#txtUserName").val() == "") {
                //                alert("请输入用户名!");
                $("#verifyresult").text("请输入用户名!");
            }
            else {
                sendData($("#txtUserName").val());
            }
        });

        // 定义一个AJAX请求方法
        function sendData(sUserName) {
            // 访问页面后台方法
            var loc = window.location.href;
            $.ajax({
                type: "POST",
                url: '<%=ResolveUrl("~/Test/GetAuto.asmx/VerifyCustomers") %>',
                // sUserName要跟请求方法CheckUserName定义的参数名称要保持一致
                // json数据格式是由一对键值构成,如{"name1":"value1", "name2":"value2"}
                data: '{ "sUserName": "' + sUserName + '"}',
                // 发送信息至服务器时内容编码类型
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msdata) {
                    // AJAX响应被包装到一个d对象里,如{"d":true}, 
                    // 因此需要用到msdata.d来获取请求返回的布尔值
                    if (msdata.d) {
                        //                        alert("验证用户成功!");
                        $("#verifyresult").text("验证用户成功!");
                    }
                    else {
                        //                        alert("验证用户已经存在!");
                        $("#verifyresult").text("验证用户已经存在!");
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert("AJAX错误:" + errorThrown);
                }
            });
        }
    });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    自动匹配:<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:Label ID="hfCustomerId" runat="server" />
    <asp:Label ID="Label1" runat="server" /><br />
    验证用户:<input type ="text" id="txtUserName" />
    <span id="verifyresult" style=" color :Red;"></span>
    </form>
</body>
</html>

用户验证方法参考:http://www.cnblogs.com/iamlixin/archive/2012/02/15/2352000.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值