javascript - 无法让 jQuery AutoComplete 与外部 JSON 一起使用

标签 javascript jquery asp.net json ihttphandler

我正在开发一个 ASP.NET 应用程序,需要 jQuery AutoComplete。目前,当我在 txt63 输入框中输入数据时,没有任何反应(在你因为我使用像 txt63 这样的名称而责备我之前,我知道,我知道......但这不是我的决定:D) .

这是我的 JavaScript 代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var theSource = '../RegionsAutoComplete.axd?PID=<%= hidden62.value %>'
$(function() {
  $('#<%= txt63.ClientID %>').autocomplete({
    source: theSource,
    minLength: 2,
    select: function(event, ui) {
      $('#<%= hidden63.ClientID %>').val(ui.item.id);
    }
  });
});

这是我的 HTTP 处理程序

Namespace BT.Handlers
    Public Class RegionsAutoComplete : Implements IHttpHandler
        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property

        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
            ''# the page contenttype is plain text'
            context.Response.ContentType = "application/json"
            context.Response.ContentEncoding = Encoding.UTF8

            ''# set page caching'
            context.Response.Cache.SetExpires(DateTime.Now.AddHours(24))
            context.Response.Cache.SetCacheability(HttpCacheability.Public)
            context.Response.Cache.SetSlidingExpiration(True)
            context.Response.Cache.VaryByParams("PID") = True

            Try
                ''# use the RegionsDataContext'
                Using RegionDC As New DAL.RegionsDataContext

                    ''# query the database based on the querysting PID'
                    Dim q = (From r In RegionDC.bt_Regions _
                            Where r.PID = context.Request.QueryString("PID") _
                           Select r.Region, r.ID)

                    ''# now we loop through the array'
                    ''# and write out the ressults'

                    Dim sb As New StringBuilder
                    sb.Append("{")

                    For Each item In q
                        sb.Append("""" & item.Region & """: """ & item.ID & """,")
                    Next
                    sb.Append("}")
                    context.Response.Write(sb.ToString)
                End Using

            Catch ex As Exception
                HealthMonitor.Log(ex, False, "This error occurred while populating the autocomplete handler")
            End Try
        End Sub


    End Class
End Namespace

我的 ASPX 页面的其余部分有适当的控件,因为我使用的是旧版本的 jQuery 库。我正在尝试让它与新的 CDN 一起工作,因为我听说“dev”CDN 即将过时。

任何帮助或指导将不胜感激。

最佳答案

好吧,经过几个小时的努力,我的 iHttpHandler 很好地传递了数据。如果您觉得这可以更好,请随时发表评论

Imports System.Linq
Imports System.Collections.Generic

Namespace BT.Handlers
    Public Class RegionsAutoComplete : Implements IHttpHandler

        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property

    Public Shared _PID As Integer

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        ''# the page contenttype is plain text'
        context.Response.ContentType = "application/json"
        context.Response.ContentEncoding = Encoding.UTF8

        ''# set query string parameters into global variables'
        Dim _term As String = If(context.Request.QueryString("term") <> "", context.Request.QueryString("term"), "")
        _PID = Integer.Parse(context.Request.QueryString("PID"))
        ''# create a string builder to store values'
        Dim sb As New StringBuilder
        sb.Append("[" & vbCrLf)

        Dim item As BTRegionsList

        Try
            ''# now we loop through the array'
            ''# and write out the ressults'
            For Each item In BT.Handlers.RegionsAutoComplete.RegionsListInstance
                ''# make sure the added items are valid to the search'
                ''# we are also doing a case insensitive search'
                If item.Region.ToLower.Contains(_term.ToLower) Then
                    ''# this is actually writing out some JSON data'
                    sb.Append(vbTab & "{ ""label"": """ & item.Region & """, ""value"": """ & item.Region & """, ""id"": """ & item.Id.ToString & """ }," & vbCrLf)
                End If
            Next
        Catch ex As Exception
            ''# log any errors to the Health Monitor'
            HealthMonitor.Log(ex, False, "This error occurred while populating the autocomplete handler")
        End Try

        sb.Append("]")

        ''# write out the string builder'
        context.Response.Write(sb.ToString)

        ''# set the string builder values to zero'
        sb.Length = 0
        sb = Nothing
        item = Nothing

    End Sub

        ''# this is the instance of the BTRegionsList object'
        Friend Shared _RegionsListInstance As List(Of BTRegionsList)
        Friend Shared UsedPID As Integer ''# this is the PID of the most recent instance
        Public Shared ReadOnly Property RegionsListInstance() As List(Of BTRegionsList)
            Get
                Dim r As New List(Of BTRegionsList)
                ''# only populate the _RegionsListInstance if it is currently empty'
                If _RegionsListInstance Is Nothing Or UsedPID = _PID Then
                    Using RegionDC As New DAL.RegionsDataContext

                        ''# query the database based on the querysting PID'
                        Dim q = (From reg In RegionDC.bt_Regions _
                                Where reg.PID = Integer.Parse(HttpContext.Current.Request.QueryString("PID")) _
                                Select reg.Region, reg.ID)
                        For Each item In q
                            r.Add(New BTRegionsList(item.ID, item.Region))
                        Next
                        _RegionsListInstance = r
                    End Using

                Else
                    ''# if _RegionsListInstance is not empty'
                    ''# then we want to set our BTRegionsList to '
                    ''# equal _RegionsListInstance'
                    r = _RegionsListInstance
                End If

                ''# Set the PID for this instance'
                UsedPID = _PID

                ''# now we return our BTRegionsList'
                Return r
            End Get
        End Property

    End Class

    ''# a singleton class to store region information'
    ''# this helps us to not have to hit the database too many times'
    Public Class BTRegionsList

        Private _Region As String
        Private _ID As Integer

        Public Property Id() As Integer
            Get
                Return _ID
            End Get
            Set(ByVal value As Integer)
                _ID = value
            End Set
        End Property

        Public Property Region() As String
            Get
                Return _Region
            End Get
            Set(ByVal value As String)
                _Region = value
            End Set
        End Property

        Public Sub New(ByVal ID As Integer, ByVal Region As String)
            _ID = ID
            _Region = Region
        End Sub

    End Class
End Namespace

关于javascript - 无法让 jQuery AutoComplete 与外部 JSON 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2931877/

相关文章:

javascript - 如何使用 javascript 或 jquery 检查命名窗口是否存在

Asp.Net 路由到通用处理程序

c# - 关于 SharePoint 2010(控件、Web 部件、主题、母版页)的所有信息

javascript - Facebook FB.logout() 是否还有对话框?

javascript - jQuery - 对通过 .text() 检索到的数字使用 .split() 会添加很多空项目

javascript - 附加 html 中的事件触发问题?

ASP.NET - 在全局资源文件中存储 SQL 查询?

javascript - 需要帮助理解令人困惑的 Typescript 功能

javascript - 在 jQuery UI 中触发鼠标拖动

javascript - 如何使用 jquery/javascript 在 html 选择选项中填充 javascript 对象值的数据