简体   繁体   English

jQuery的自动完成来填充一个JavaScript数组?

[英]jquery autocomplete to fill a javascript array?

I wanted to add autocomplete to a text box I had on my form. 我想向表单上的文本框添加自动填充功能。 I found an excellent SO thread that entailed this right here: https://stackoverflow.com/a/5973017/168703 This was exactly what I needed because it also only showed the autocomplete when someone typed an @ symbol. 我在这里找到了一个出色的SO线程,需要执行此操作: https : //stackoverflow.com/a/5973017/168703这正是我所需要的,因为它仅在有人键入@符号时显示自动完成功能。

It was something to the effect of this: 产生了以下效果:

$("#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;
    }
});

Pay close attention to the source portion as it forced me to declare something like this: 请密切注意source部分,因为它迫使我声明如下内容:

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

                        ];

That is my autocomplete suggestions would be inside of the js file...but this is the only part I did not want. 那是我的自动完成建议会在js文件中...但这是我唯一不想要的部分。 I have to load the data from a database. 我必须从数据库加载数据。 Unfortunately I am dealing with an ancient .net framework prolly pre 2.0 app. 不幸的是,我正在处理一个古老的.net framework prol pre 2.0应用程序。 Its vb.net and there is no linq or lists or all the good stuff. 它的vb.net并且没有linq或列表或所有好东西。 Fine I thought..I could probably create a .asmx file that added strings to an array list, converted it back to a string array and returned it in the .asmx file. 很好,我想..我可能可以创建一个.asmx文件,该文件将字符串添加到数组列表中,将其转换回字符串数组,然后将其返回到.asmx文件中。 Something to this effect (this was just a test no pulling data just yet from a database): 某种效果(这只是一项测试,目前还没有从数据库中提取数据):

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

As mentioned this was just a test so I'm just adding two items in a string array and returning it. 如前所述,这只是一个测试,所以我只是在字符串数组中添加两个项目并返回它。 Now I am pretty unsure how to change my jquery code to incorporate this.... I thought I would add something like this: 现在我很不确定如何更改我的jquery代码以合并此内容。...我想我会添加如下内容:

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

But I am not sure how to incorporate that in the original jquery as my jquery skills are zilch... Can anyone help me understand this and put this together so it may actually work. 但是我不确定如何将其合并到原始jquery中,因为我的jquery技能是zilch ...谁能帮助我理解这一点并将其放在一起,以便它实际上可以工作。 Once I get the test working I can then modify it to pull data from the database. 一旦测试成功,我便可以对其进行修改以从数据库中提取数据。 Am I on the right path? 我在正确的道路上吗?

EDIT 编辑

Here's what I have 这就是我所拥有的

$("#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;
    }
});

But my app is throwing an internal server error 500. With the following exception: 但是我的应用抛出了内部服务器错误500。以下异常除外:

System.InvalidOperationException: Request format is invalid: application/json; System.InvalidOperationException:请求格式无效:application / json; charset=UTF-8. 字符集= UTF-8。 at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.Invoke() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() 在System.Web.Services.Protocols.WebServiceHandler.Invoke()处在System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()在System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

Here is my webservice: 这是我的网络服务:

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

Again this is an old 1.1 .net application, do I need something in the web config file to represent this .asmx file? 同样,这是一个旧的1.1 .net应用程序,我是否需要Web配置文件中的某些内容来表示此.asmx文件? The parameters in the web method match the parameters of the ajax call so what could be causing this? web方法中的参数与ajax调用的参数匹配,那么可能是什么原因引起的呢?

I think the problem here is that web services expect XML or text. 我认为这里的问题是Web服务需要XML或文本。 JSON won't work. JSON不起作用。

You can try changing your content-Type (in your ajax call) to text and returning a string instead of a string array from your GetLogins method. 您可以尝试将您的content-Type(在ajax调用中)更改为文本,然后从GetLogins方法返回字符串而不是字符串数组。 That way you can serialize your string array to a JSON string using a JSON converter and return that. 这样,您可以使用JSON转换器将字符串数组序列化为JSON字符串,然后将其返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM