【问题标题】:jQuery autocomplete not works with remote data from ashxjQuery 自动完成功能不适用于来自 ashx 的远程数据
【发布时间】:2025-12-09 09:05:02
【问题描述】:

我使用带有 ASHX 作为源的 jQuery 自动完成功能。但是每个请求都会抛出一个编号为 200 的错误。

我的 JavaScript:

$(function () {
    $('#username input[type = "text"]').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "UserName.ashx?term=" + request.term,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.Value
                        }
                    }))
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }
    });
});

HTML:

<div id="username">
    <asp:Label Text="User name" runat="server" />
    <asp:TextBox ID="txtUserName" runat="server" />
</div>

ASHX:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.Clear()
    context.Response.ContentType = "application/json"

    Try
        Dim oList As New List(Of ResultItem)

        For Each File As System.IO.FileInfo In New System.IO.DirectoryInfo(ApplicationInfo.Settings.AbsoluteUserConfigPath).GetFiles(context.Request.QueryString("term") & "*.xml")
            oList.Add(New ResultItem With {.Value = System.Text.RegularExpressions.Regex.Replace(File.Name, File.Extension & "$", String.Empty)})
        Next

        context.Response.Write(New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(oList))
    Catch ex As Exception
        context.Response.Clear()
        context.Response.ContentType = "text/plain"
        context.Response.StatusCode = 500
        context.Response.StatusDescription = ex.Message
    End Try
End Sub

对于静态内容,它可以正常工作,但是对于这个请求,我收到以下错误:SyntaxError: JSON.parse: unexpected character

生成的 JSON 看起来像

[
    {"Value":"Item 1","Name":"","Description":""},
    {"Value":"Item 2","Name":"","Description":""},
    {"Value":"Item 3","Name":"","Description":""},
    {"Value":"Item 4","Name":"","Description":""}
]

并且应该是有效的。

知道为什么它不起作用吗?出乎意料的角色是什么?

感谢您的回复。

【问题讨论】:

    标签: vb.net jquery jquery-autocomplete ashx


    【解决方案1】:

    我更改了源和 JSON,然后运行它。

    $(function () {
        $('#username input[type = "text"]').autocomplete({
            source: "UserName.ashx"
        });
    }
    
    [
        {"object":"Item 1","label":"","Description":""},
        {"object":"Item 2","label":"","Description":""},
        {"object":"Item 3","label":"","Description":""},
        {"object":"Item 4","label":"","Description":""}
    ]
    

    【讨论】:

      最近更新 更多