javascript - jquery 自动完成填充 javascript 数组?

标签 javascript jquery asp.net

我想为表单上的文本框添加自动完成功能。我在这里找到了一个很好的 SO 线程:https://stackoverflow.com/a/5973017/168703这正是我所需要的,因为它也只在有人输入 @ 符号时显示自动完成。

结果是这样的:

$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
        event.preventDefault();
    }
}).autocomplete({
    minLength: 0,
    source: function(request, response) {       
        var term = request.term,
            results = [];
        if (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            } else {
                results = ['Start typing...'];
            }
        }
        response(results);
    },
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        var email = GetEmail(ui.item.value);
        email = email + ";";
        emails.push(email);
        $("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join("");
        return false;
    }
});

请密切注意 source 部分,因为它迫使我声明如下内容:

var availableTags = [
                            "jdoe",
                            "tsmith",
                            "mrighty",
                            "tstevens",
                            "ktripp",
                            "tram",

                        ];

那是我的自动完成建议将在 js 文件中...但这是我唯一不想要的部分。我必须从数据库加载数据。不幸的是,我正在处理一个古老的 .net 框架 prolly pre 2.0 应用程序。它是 vb.net,没有 linq 或列表或所有好东西。很好,我想..我可以创建一个 .asmx 文件,将字符串添加到数组列表,将其转换回字符串数组并将其返回到 .asmx 文件中。达到这种效果的东西(这只是一个测试,还没有从数据库中提取数据):

Imports System.Web.Services
Imports System.Collections


<System.Web.Services.WebService(Namespace := "http://tempuri.org/myapp.com/GetLogins")> _
Public Class GetLogins
    Inherits System.Web.Services.WebService

#Region " Web Services Designer Generated Code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Web Services Designer.
        InitializeComponent()

        'Add your own initialization code after the InitializeComponent() call

    End Sub

    'Required by the Web Services Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Web Services Designer
    'It can be modified using the Web Services Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        components = New System.ComponentModel.Container()
    End Sub

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        'CODEGEN: This procedure is required by the Web Services Designer
        'Do not modify it using the code editor.
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

#End Region

    ' WEB SERVICE EXAMPLE
    ' The HelloWorld() example service returns the string Hello World.
    ' To build, uncomment the following lines then save and build the project.
    ' To test this web service, ensure that the .asmx file is the start page
    ' and press F5.
    '

    'Public Function HelloWorld() As String
    '   Return "Hello World"
    'End Function
    <WebMethod()> _
    Public Function GetLogins() As String()
        Dim myList As ArrayList
        myList.Add("jstevens")
        myList.Add("jdoe")

        Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
        Return arr
    End Function
End Class

如前所述,这只是一个测试,所以我只是在字符串数组中添加两个项目并返回它。现在我很不确定如何更改我的 jquery 代码以合并此.... 我想我会添加这样的东西:

$.ajax({
            url: "GetLogins.asmx/GetLogins",
            data: "{ 'resName': '" + request.term + "' }",
            datatype: "json",
            type= "POST",
            contentType: "application/json; charset=utf-8"
            })

但我不确定如何将其合并到原始 jquery 中,因为我的 jquery 技能很烂...... 任何人都可以帮助我理解这一点并将其放在一起以便它可能真正起作用。一旦我让测试工作,我就可以修改它以从数据库中提取数据。我走在正确的道路上吗?

编辑

这是我的

$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
        event.preventDefault();
    }
}).autocomplete({
    minLength: 0,
   source: function (request, response) {
        //get client value
        var c = $("#ucAddActionItemIssueActions_ddlClientAssignTo").val();
        var params= '{"ClientID":"' + c + '"}';
        $.ajax({
            url: "GetLogins.asmx/GetLogins",
            data: params,
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.name
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });},
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        var email = GetEmail(ui.item.value);
        email = email + ";";
        emails.push(email);
        $("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join("");
        return false;
    }
});

但我的应用程序抛出内部服务器错误 500。有以下异常:

System.InvalidOperationException: Request format is invalid: application/json; charset=UTF-8. at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.Invoke() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

这是我的网络服务:

Imports System.Web.Services
Imports System.Collections
<System.Web.Services.WebService(Namespace := "http://tempuri.org/quikfix.jakah.com/GetLogins")> _
Public Class GetLogins
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function GetLogins(ByVal ClientID As Integer) As String()
        Dim myList As New ArrayList
        myList.Add("jstevens")
        myList.Add("jdoe")
        myList.Add("smartin")

        Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
        Return arr
    End Function
End Class

同样,这是一个旧的 1.1 .net 应用程序,我需要在 Web 配置文件中添加一些内容来表示这个 .asmx 文件吗? Web 方法中的参数与 ajax 调用的参数匹配,那么可能是什么原因造成的?

最佳答案

我认为这里的问题是 Web 服务需要 XML 或文本。 JSON 将不起作用。

您可以尝试将您的内容类型(在您的 ajax 调用中)更改为文本并从您的 GetLogins 方法返回一个字符串而不是字符串数组。这样您就可以使用 JSON 转换器将字符串数组序列化为 JSON 字符串并返回它。

关于javascript - jquery 自动完成填充 javascript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14937884/

相关文章:

javascript - 服务器端调用未显示 Fancybox

asp.net - 系统内存不足异常 : Exception when uploading a file

javascript - 带有指令的 Angular ngModel

javascript - 使用 Java/Scala 压缩 CSS/Javascript

javascript - 使用逗号分隔值巧妙地获取查询字符串

javascript - 如何在不删除其子项的情况下删除 div?

javascript - 同位素回调函数

asp.net - 更快地提供静态文件(例如 JavaScript、CSS 和图像)的技巧

javascript - CSS 动画到 javascript 幻灯片

javascript - 如何使用javascript调用按钮点击事件背后的代码