自动完成 jQuery 1.8-UI JSON 格式

发布于 2024-08-26 18:01:03 字数 1743 浏览 7 评论 0原文

我正在尝试 jQuery 1.8-UI 中的新自动完成功能。我提供了以下格式的数据:

["val1", "val2", "val3"]

这来自存储过程,但输出为字符串。由于某种原因,这根本不起作用,但是,如果我使用 javascript 变量提供相同的数据,

var data = ["val1", "val2", "val3"];

那么这工作正常。

<script type="text/javascript">
  $(function()
    $("#txtClient").autocomplete({
      source: "/intranet/common/scripts/IntranetLists.aspx?ListType=C"
    });
  });
</script>

我有一个页面,它使用查询字符串提供我想要的任何数据。它是临时的,但是当我之前使用 bassistence 的自动完成 时它就起作用了。

有什么想法吗?


编辑

源只是在单独的行上输出一个条目。现在输出采用 JSON 格式。我不明白的是输入如何提供数据作为对数据源的查询。正如我所说,我使用的脚本应该在每次输入新密钥时被调用。

这是我得到的代码(考虑到这与第三方自动完成插件配合得很好)

<%
  Dim MyCmd As New dbExact("proc_Intranet_Lists")
  MyCmd.cmd.Parameters("@List").Value = Request.QueryString("ListType")
  If Request.QueryString("Top") <> Nothing Then
    MyCmd.cmd.Parameters("@Top").Value = Request.QueryString("Top")
  End If
  MyCmd.cmd.Parameters("@Code").Value = Request.QueryString("term")
  MyCmd.cmd.Connection.Open()

  Dim results As New StringBuilder()
  results.Append("[")
  Dim dr As SqlDataReader = MyCmd.cmd.ExecuteReader
  If dr.HasRows Then
    While dr.Read
      results.AppendLine("'" + dr(0).ToString() + "',")
    End While
  Else
    results.Append("None Found")
  End If
  results.Remove(results.Length - 2, 2)
  results.Append("]")
  Response.Write(results.ToString())
  results = Nothing
  MyCmd.cmd.Connection.Close()
  MyCmd = Nothing
%>

新自动完成的文档没有在任何地方说明传递的查询字符串实际上称为“term”(我从search.php 文件)。我正在 VB.NET 中执行此操作。

I'm toying with the new autocomplete in jQuery 1.8-UI. I've provided data in the following format

["val1", "val2", "val3"]

This is coming from a stored procedure but output as a string. For some reason this doesn't work at all, however, if I supply the same data using a javascript variable

var data = ["val1", "val2", "val3"];

Then this works fine.

<script type="text/javascript">
  $(function()
    $("#txtClient").autocomplete({
      source: "/intranet/common/scripts/IntranetLists.aspx?ListType=C"
    });
  });
</script>

I've got a page which supplies whatever data I want using query strings. It's more temporary, but it worked when I previously used bassistence's autocomplete.

Any ideas?


EDIT

The source simply outputs an entry on separate lines. Now the output does it with JSON format. What I don't understand is how the input provides the data as a query to the source of data. As I say, I'm using a script which should get called every time I enter a new key.

Here's the code I've got (take into account this worked fine with a third-party autocomplete plugin)

<%
  Dim MyCmd As New dbExact("proc_Intranet_Lists")
  MyCmd.cmd.Parameters("@List").Value = Request.QueryString("ListType")
  If Request.QueryString("Top") <> Nothing Then
    MyCmd.cmd.Parameters("@Top").Value = Request.QueryString("Top")
  End If
  MyCmd.cmd.Parameters("@Code").Value = Request.QueryString("term")
  MyCmd.cmd.Connection.Open()

  Dim results As New StringBuilder()
  results.Append("[")
  Dim dr As SqlDataReader = MyCmd.cmd.ExecuteReader
  If dr.HasRows Then
    While dr.Read
      results.AppendLine("'" + dr(0).ToString() + "',")
    End While
  Else
    results.Append("None Found")
  End If
  results.Remove(results.Length - 2, 2)
  results.Append("]")
  Response.Write(results.ToString())
  results = Nothing
  MyCmd.cmd.Connection.Close()
  MyCmd = Nothing
%>

The documentation for the new autocomplete doesn't state anywhere that the query string passed is actually called "term" (which I found out from the search.php file). I'm doing this in VB.NET.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

分開簡單 2024-09-02 18:01:03

实际上,我应该为此编写一个教程,因为周围没有太多文档。如果您想在 jQuery-UI 1.8 中使用 jQuery 的新自动完成功能,那么您可以按照以下步骤操作。

就我个人而言,我使用了通用的 Web 处理程序。我认为这些更好,因为它们不经过常规请求管道,而是只有两个“元素”、一个属性和一个名为 ProcessRequest 的子例程。

我这样做的方式是编写一个存储过程,它采用设置参数来确定我想要的自动完成内容。例如,如果我想使用自动完成器列出一些国家/地区,或者我想使用它列出员工姓名,那么我会传递特定的查询字符串来确定我想要返回的内容。这使得它非常灵活。

<%@ WebHandler Language="VB" Class="Autocomplete" %>

Imports System
Imports System.Web
Imports System.Collections.Generic
Imports System.Web.Script.Serialization

Public Class Autocomplete : Implements IHttpHandler

  Public Class AutocompleteItem
    Public id As String
    Public value As String
  End Class

  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.ContentType = "text/plain"

    Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("YourConnectionString").ToString)
    Dim cmd As New SqlCommand("YourStoredProcedure", conn)
    cmd.CommandType = CommandType.StoredProcedure
    With cmd.Parameters
      .Add(New SqlParameter("@List", 22, 10, 1, False, 0, 0, "", 512, context.Request.QueryString("ListType")))
      .Add(New SqlParameter("@Code", 22, 12, 1, False, 0, 0, "", 512, context.Request.QueryString("term")))
      .Add(New SqlParameter("@Top", 16, 0, 1, False, 0, 0, "", 512, context.Request.QueryString("Top")))
    End With
    conn.Open()

    Dim results As New StringBuilder()
    Dim dr As SqlDataReader = cmd.ExecuteReader
    Dim items As New List(Of AutocompleteItem)
    Dim serializer As New JavaScriptSerializer()

    While dr.Read
      Dim autocomplete As New AutocompleteItem
      autocomplete.id = dr(0)
      autocomplete.value = dr(1)
      items.Add(autocomplete)
    End While

    Dim arrayJson As String = serializer.Serialize(items)
    context.Response.Write(arrayJson)
    conn.Close()
  End Sub

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

我确信还有很多其他方法可以做到这一点,但这正是对我有用的方法。我使用 AutocompleteItem CDT 因为命名变量是 jQuery 的自动完成中使用的变量。默认情况下,它使用idvalue。您可以指定您想要的任何其他内容,但是您必须使用 jQuery 中提供的事件自行格式化您的项目。

幸运的是,.NET 允许您序列化数据,但您也可以在 PHP 中使用 json_encode 执行此操作。您可以在 jQuery UI 下载中找到 PHP 示例。

最后,这是我使用的 jQuery。我的延迟为零,因为它是一个快速的本地服务器。

<script type="text/javascript">
    $(function() {
      $("#txtClient").autocomplete({
        source: "/intranet/common/scripts/Autocomplete.ashx?ListType=Addresses",
        minLength: 2,
        delay: 0
      });
    });
</script>

希望这会对您使用 jQuery UI 1.8 的自动完成功能有所帮助。

编辑 如果有人对如何改进通用处理程序有任何建议,请随时向我展示。我注意到我每次都会重新实例化 AutocompleteItem 对象,但是如果您不这样做,它将由于某种原因保留旧值,尽管使用新值重新初始化变量。干杯。

Realistically, I should write a tutorial up for this because there's not much documentation around. If you want to use jQuery's new Autocomplete in jQuery-UI 1.8 then here's how you do it.

Personally, I used a generic web handler. I'm under the assumption these are better because they don't go through the regular request pipeline and instead only have two "elements", a property, and a sub-routine called ProcessRequest.

The way I do it is I've written a stored procedure which takes set arguments to determine what autocomplete I want. For example, if I want to use the autocompleter to list some countries, or I want to use it to list the names of employees, then I pass a certain query string to determine what I want back. This makes it very flexible.

<%@ WebHandler Language="VB" Class="Autocomplete" %>

Imports System
Imports System.Web
Imports System.Collections.Generic
Imports System.Web.Script.Serialization

Public Class Autocomplete : Implements IHttpHandler

  Public Class AutocompleteItem
    Public id As String
    Public value As String
  End Class

  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.ContentType = "text/plain"

    Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("YourConnectionString").ToString)
    Dim cmd As New SqlCommand("YourStoredProcedure", conn)
    cmd.CommandType = CommandType.StoredProcedure
    With cmd.Parameters
      .Add(New SqlParameter("@List", 22, 10, 1, False, 0, 0, "", 512, context.Request.QueryString("ListType")))
      .Add(New SqlParameter("@Code", 22, 12, 1, False, 0, 0, "", 512, context.Request.QueryString("term")))
      .Add(New SqlParameter("@Top", 16, 0, 1, False, 0, 0, "", 512, context.Request.QueryString("Top")))
    End With
    conn.Open()

    Dim results As New StringBuilder()
    Dim dr As SqlDataReader = cmd.ExecuteReader
    Dim items As New List(Of AutocompleteItem)
    Dim serializer As New JavaScriptSerializer()

    While dr.Read
      Dim autocomplete As New AutocompleteItem
      autocomplete.id = dr(0)
      autocomplete.value = dr(1)
      items.Add(autocomplete)
    End While

    Dim arrayJson As String = serializer.Serialize(items)
    context.Response.Write(arrayJson)
    conn.Close()
  End Sub

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

I'm sure there's many other ways of doing this, but this is just what worked for me. I use the AutocompleteItem CDT because the named variables are what are used in jQuery's Autocomplete. By default, it uses id and value. You can specify anything else you want, but then you have to go and format your items yourself using the events provided in jQuery.

Fortunately .NET lets you serialize the data, but you can do so in PHP as well using json_encode. You can find the PHP example in the jQuery UI download.

Finally, here's the jQuery I used. I have a zero delay because it's a fast, local server.

<script type="text/javascript">
    $(function() {
      $("#txtClient").autocomplete({
        source: "/intranet/common/scripts/Autocomplete.ashx?ListType=Addresses",
        minLength: 2,
        delay: 0
      });
    });
</script>

Hopefully this will help you when using jQuery UI 1.8's Autocomplete.

EDIT If anyone has any recommendations on how to improve the generic handler, feel free to showo me. I notice I'm re-instantiating the AutocompleteItem object each time, however if you don't do this it will keep the old values for some reason, despite re-initializing the variables with new values. Cheers.

清君侧 2024-09-02 18:01:03

我发现 JSON 格式非常简单。您可以使用此页面上的演示查看 Firebug 中的响应:http://jqueryui。 com/demos/autocomplete/#event-change .. 这是一个示例:

[ 
{ "id": "Erithacus rubecula", "label": "European Robin", "value": "European Robin" }, 
{ "id": "Cercotrichas galactotes", "label": "Rufous-Tailed Scrub Robin", "value": "Rufous-Tailed Scrub Robin" }, 
{ "id": "Irania gutturalis", "label": "White-throated Robin", "value": "White-throated Robin" }, 
{ "id": "Turdus migratorius", "label": "American Robin", "value": "American Robin" }
]

I found the JSON format pretty simple. You can check out the responses in firebug using the demo on this page : http://jqueryui.com/demos/autocomplete/#event-change .. here's one example :

[ 
{ "id": "Erithacus rubecula", "label": "European Robin", "value": "European Robin" }, 
{ "id": "Cercotrichas galactotes", "label": "Rufous-Tailed Scrub Robin", "value": "Rufous-Tailed Scrub Robin" }, 
{ "id": "Irania gutturalis", "label": "White-throated Robin", "value": "White-throated Robin" }, 
{ "id": "Turdus migratorius", "label": "American Robin", "value": "American Robin" }
]
一身骄傲 2024-09-02 18:01:03

你的例子还不够清楚。但是如果您使用 php 来填充自动完成变量,我只会在 javascript 中回显它:

Js:

var data = <?php echo $autocomplete ?>;

PHP

$autocomplete = '["val1", "val2", "val3"]';

但我不确定这是否是您正在寻找的答案。

Your example isn't really clear enough. But if you would use php to fill the autocomplete variables I would just echo it in the javascript:

Js:

var data = <?php echo $autocomplete ?>;

PHP

$autocomplete = '["val1", "val2", "val3"]';

But I'm not sure if this is the answer you are looking for.

内心荒芜 2024-09-02 18:01:03
$( "#someid" ).autocomplete({
     source: "something.php(aspx)?param1=param1¶m2=param2¶m3=param3",
     minLength: 1,
     select: function( event, ui ) {
         alert( "value: " + ui.item.value + " , id: " + ui.item.id );
     }
});
$( "#someid" ).autocomplete({
     source: "something.php(aspx)?param1=param1¶m2=param2¶m3=param3",
     minLength: 1,
     select: function( event, ui ) {
         alert( "value: " + ui.item.value + " , id: " + ui.item.id );
     }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文