【问题标题】:JQuery AutoComplete textbox Returning ErrorJQuery自动完成文本框返回错误
【发布时间】:2013-02-23 02:52:29
【问题描述】:

我曾尝试使用 jquery 和下面提到的代码来做自动完成文本框,但我无法实现它,我在 jquery 中遇到错误。提前致谢。

AutoCompleteTextBox.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>

<!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>Ajax Auto Complete Using Jquery</title>

      <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">
     var UserNameInput;

     $(document).ready(function () {

            $("#<%=txtName.ClientID %>").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        //contentType: "application/json; charset=utf-8",
                        url: "AutoCompleteTextBox.aspx/getUserNames",
                        data: "{'TextBoxVal':'" + document.getElementById('<%=txtName.ClientID%>').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("success");
                        },
                        error: function (result) {
                            alert("error ");
                        }
                    });
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr>
    <td>
    <div>
    User Name : &nbsp;&nbsp;
        <asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
    </div>
    </td>
    </tr>
    </table>
    </form>
</body>
</html>

AutoCompleteTextBox.aspx.cs :

public List<string> getUserNames(string TextBoxVal)
    {
        string strCon;
        List<string> objList = new List<string>();
        strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%"+TextBoxVal+"%'", con);
        con.Open();
        SqlDataReader objReader = cmd.ExecuteReader();

        while (objReader.Read())
        {
            objList.Add(objReader["EmpName"].ToString());
        }
        Response.Write(objList.ToString());
        con.Close();
        return objList;

    }

【问题讨论】:

  • 你遇到了什么错误?
  • 500 内部服务器错误“/”应用程序中的服务器错误。未知的 Web 方法 getUserNames。异常详细信息:System.ArgumentException:未知的网络方法 getUserNames

标签: asp.net .net c#-4.0 jquery


【解决方案1】:

我不知道您遇到了什么样的错误,但是您是否尝试过评论下面的行? 您已经在发送响应,无需显式编写响应。 您可能还想将您的方法转换为 Web 方法。

 Response.Write(objList.ToString());

【讨论】:

  • 500 内部服务器错误“/”应用程序中的服务器错误。未知的 Web 方法 getUserNames。异常详细信息:System.ArgumentException:未知的网络方法 getUserNames
【解决方案2】:

你应该像这样制作这个方法:

[WebMethod]
public List<string> getUserNames(string TextBoxVal)
{
    string strCon;
    List<string> objList = new List<string>();
    strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
    SqlConnection con = new SqlConnection(strCon);
    SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%"+TextBoxVal+"%'", con);
    con.Open();
    SqlDataReader objReader = cmd.ExecuteReader();

    while (objReader.Read())
    {
        objList.Add(objReader["EmpName"].ToString());
    }
    //Response.Write(objList.ToString());
    //remove the above because you can not use Resonse.Write here
    con.Close();
    return objList;

}

尝试使用 firebug 插件,这将为您提供有关您遇到的错误的大量信息

【讨论】:

  • 我删除了 response.write 但错误仍然存​​在,在 firefox 中 xhr 显示 200 ok 但在 jquery 中显示错误警报,
  • 我没有使用 Web 服务,我使用的是同一页面(AutoCompleteTextBox.aspx 和 AutoCompleteTextBox.aspx.cs)
  • 您可以在您的 asp.net 应用程序开始的任何代码中包含 [WebMethod]
  • 是的,我添加了,但我收到 500 internal server error 。我使用火虫发现了这个错误。该错误看起来像“/”应用程序中的服务器错误。未知的 Web 方法 getUserNames。异常详细信息:System.ArgumentException:未知的 Web 方法 getUserNames。
【解决方案3】:

为此,我没有调用 AutoCompleteTextBox.aspx 页面,而是添加了一个新服务并调用了 asmx 页面,并在 asmx.cs 页面中添加了这段代码

[System.Web.Script.Services.ScriptService()]

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

namespace Ajax_Using_Jquery
{
    /// <summary>
    /// Summary description for AutoCompleteFetchService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService()]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class AutoCompleteFetchService : System.Web.Services.WebService
    {


        [WebMethod]
        public List<string> getUserNames(string TextBoxVal)
        {
            string strCon;
            List<string> objList = new List<string>();
            strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%" + TextBoxVal + "%'", con);
            con.Open();
            SqlDataReader objReader = cmd.ExecuteReader();

            while (objReader.Read())
            {
                objList.Add(objReader["EmpName"].ToString());
            }

            con.Close();
            return objList;

        }

    }
}

在我编码的 aspx 页面中,

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>

<!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>Ajax Auto Complete Using Jquery</title>
    <script type="text/javascript" src="JQuery/jquery-1.9.0.mini.js"></script>
    <script type="text/javascript" src="JQuery/jquery-ui.min.js" ></script>
     <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">
     $(document).ready(function () {
         $(".autosuggest").autocomplete({
             source: function (request, response) {
                 $.ajax({
                     type: "POST",
                     contentType: "application/json; charset=utf-8",
                     url: "AutoCompleteFetchService.asmx/getUserNames",
                     data: "{'TextBoxVal':'" + document.getElementById('txtName1').value + "'}",
                     dataType: "json",
                     success: function (data1) {
                         response(data1.d);
                         if (data1.d == "" || data1.d == null || typeof (data1.d) == 'undefined') {

                             response(["no search found"]);
                         }
                     },
                     error: function (XMLHttpRequest, textStatus, errorThrown) {
                         alert("error " + XMLHttpRequest);
                         alert("error " + textStatus);
                         alert("error " + errorThrown);
                     }
                 });
             }
         });
     });
    </script>
  <%--  <link href="StyleSheet/jquery-ui.css" type="text/css" rel="Stylesheet" />--%>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr>
    <td>
    <div>
    User Name : &nbsp;&nbsp;
        <input type="text" id="txtName1" class="autosuggest"  />
    </div>
    </td>
    </tr>
    </table>
    </form>
</body>
</html>

【讨论】:

  • 不要使用内联SQL参数,你会容易出现SQL注入。使用 SqlParameter 避免 sql 注入。 xkcd.com/327
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2017-08-26
  • 2014-12-15
相关资源
最近更新 更多