2

我想在表单上的文本框中添加自动完成功能。我在这里找到了一个很好的 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 技能是 zilch ... 任何人都可以帮助我理解这一点并将其放在一起,以便它可以实际工作。一旦我得到测试工作,我就可以修改它以从数据库中提取数据。我在正确的道路上吗?

编辑

这就是我所拥有的

$("#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:请求格式无效:application/json;字符集=UTF-8。在 System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() 在 System.Web.Services.Protocols.WebServiceHandler.Invoke() 在 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 调用的参数相匹配,那么可能导致这种情况的原因是什么?

4

1 回答 1

0

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

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

于 2013-02-28T21:13:16.033 回答