关于自动填充文本框

时间:2014-11-17 10:37:20

标签: javascript asp.net ajax jquery-ui

##关于自动填充文本框##

在下面的代码中,我希望自动填充文本框首先从数据库中搜索,如果数据无法从数据库中找到,则从asp.net中的google api进行搜索,但在这种情况下,搜索来自数据库和谷歌api的数据。

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">

$(function () {
        $('#Address').autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Root.aspx/GetAutoCompleteData",
                    data: "{'Address':'" + document.getElementById('Address').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                        if (response(data.d) == null) {
                            var svalue = /** @type {HTMLInputElement} */(document.getElementById('Address'));
                            var svalueBox = new google.maps.places.SearchBox(/** @type {HTMLInputElement} */(svalue));
                        }
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    });

<input id="Address" type="text" style="width: 305px" placeholder="From..."/>

[WebMethod]
    public static List<string> GetAutoCompleteData(string Address)
    {
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]))
        {
            using (SqlCommand cmd = new SqlCommand("select DISTINCT Address from Locations where Address LIKE '%'+@SearchText+'%'", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", Address);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["Address"].ToString());
                }

                return result;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
    var data = {};
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    //google.maps.event.addDomListener(window, 'load', InitializeMap);
    function InitializeMap() {
        directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        var latlng = new google.maps.LatLng(21.7679, 78.8718);
        var myOptions =
        {
            zoom: 4,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var svalue = /** @type {HTMLInputElement} */(document.getElementById('<%=txtSearch.ClientID %>'));
        var svalueBox = new google.maps.places.SearchBox(/** @type {HTMLInputElement} */(svalue));
    }
    $(document).ready(function () {
        $("#<%=txtSearch.ClientID %>").autocomplete({
            source: function (request, response) {
            debugger
                $.ajax({
                    url: '<%=ResolveUrl("~/bw.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                    debugger
                        if (data.d.length == 0) {
                            $('.ui-autocomplete').hide();
                            InitializeMap();
                        }
                        else {
                            $(".pac-container").remove();
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                                }
                            }))
                        }
                    },
                    error: function (response) {
                    debugger
                        alert(response.responseText);
                    },
                    failure: function (response) {
                    debugger
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
            debugger
                $("#<%=hfCustomerId.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>

<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</form>

[WebMethod]
    public static 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())
            {
                cmd.CommandText = "select Address,LocationID from Locations where " + "Address like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(string.Format("{0}-{1}", sdr["Address"], sdr["LocationID"]));
                    }
                }
                conn.Close();
            }
            return customers.ToArray();
        }
    }