通过javascript调用C#webservice

时间:2015-03-02 14:02:06

标签: javascript c# asp.net json web-services

我在下面的网址上存放了一个C#[Web Method],但我似乎没有运气。返回值为List<string>。我这次服务电话的错误是什么?“

Asp.Net设计师

<script type="text/javascript">
    $(document).ready(function () {
        SearchText();
    });
    function SearchText() {
        $(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: "http://staging.ws/service.asmx/AutoDatax",
                    data: "{'searchText':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        alert(data.d);
                    },
                    error: function (xhr, msg, e) {
                        alert(xhr.response);
                    }
                });
            }
        });
    }
</script>

<div class="ui-widget">
    <label>Search:</label>
    <input  id="txtSearch" name="txtSearch" value="<% =searchTerm  %>"" class="autosuggest" />
    <asp:Button ID="searchButton" runat="server" class="standardButton" OnClick="searchButton_Click" Text="Search"/>
</div>

这是网络服务

[WebService(Namespace = "http://microsoft.com/webservices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    static string db = Connect.Connect("Search", false);
    [WebMethod]
    public List<string> AutoDatax(string searchText)
    {
        List<string> result = new List<string>();
        using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(db))
        {
            using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM [Table] WHERE SearchTerm LIKE @SearchText + '%';", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", searchText);
                System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["SearchTerm"].ToString());
                }
                return result;
            }
        }
    }
}

0 个答案:

没有答案