jQuery 自动完成填充数组

发布于 2024-10-08 02:12:23 字数 825 浏览 1 评论 0原文

我正在尝试使用 jQuery 的自动完成功能,在阅读了几篇文章后,我仍然有两个问题:

1)我已经获得了自动完成功能,可以使用底部发布的代码,但是我需要填充标题为“data”的数组来自我们的数据库。我一直在尝试使用不同的方法通过 AJAX 来填充此内容。我尝试使用 $.get 和 $.ajax。完成此操作的正确语法是什么?

2)这个数组会很大,如果我只填充一次数组,我就会有60,000多个值。我想知道是否可以在每次用户输入新字母时执行 AJAX 请求来填充数组?这样做更好,还是一次性用所有值填充数组?哪个更好,哪个对系统的税收更少?

//This code works
<script type="text/javascript">
  $(document).ready(function(){
  var data = "Facebook Gowalla Foursquare".split(" ");
  $("#search_company").autocomplete(data);
  });
</script>


//display company live search
echo('<form id="form" method="post" action="competitor_unlink.php" onsubmit="return">');
echo('Company: <input id="search_company"/>');
echo('<br/>');
echo('<button type="submit" value="Submit">Submit</button>');
echo('</form>');

I'm attempting to use jQuery's autocomplete feature, and after reading several posts I still have two questions:

1) I've gotten autocomplete to work with the code posted at the bottom, however I need the array titled "data" to be filled from our database. I've been trying to use different methods to fill this via AJAX. I tried using $.get and $.ajax. What is the correct syntax to accomplish this?

2) This array will be big, I will have 60,000 plus values if I just fill the array once. I was wondering if it's possible to perform an AJAX request to fill the array every-time the user enters a new letter? Is this better to do, or just fill the array with all values at once? By better, which taxes the system less?

//This code works
<script type="text/javascript">
  $(document).ready(function(){
  var data = "Facebook Gowalla Foursquare".split(" ");
  $("#search_company").autocomplete(data);
  });
</script>


//display company live search
echo('<form id="form" method="post" action="competitor_unlink.php" onsubmit="return">');
echo('Company: <input id="search_company"/>');
echo('<br/>');
echo('<button type="submit" value="Submit">Submit</button>');
echo('</form>');

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

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

发布评论

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

评论(4

绅刃 2024-10-15 02:12:23

看看这个演示 - 这就是您想要做的(使用 ajax 获取数据):

http:// /jqueryui.com/demos/autocomplete/#remote

您可以从本地拉取数据
和/或远程源:本地就好
对于小数据集(例如地址
书有 50 个条目),远程是
大数据集所必需的,例如
拥有数百或数百万条信息的数据库
可供选择的条目。

可以自定义自动完成功能以使其工作
与各种数据源,只需
指定源选项。一个数据
来源可以是:

一个带有本地数据字符串的数组,
指定一个 URL 回调本地
数据可以是一个简单的字符串数组,
或者它包含每个项目的对象
在数组中,带有标签或
值属性或两者。标签
属性显示在
建议菜单。该值将是
之后插入到输入元素中
用户从中选择了一些东西
菜单。如果只有一个属性
指定,它将用于两者,
例如。如果你只提供
值属性,该值也将
用作标签。

当使用字符串时,
自动完成插件期望
指向 URL 资源的字符串
将返回 JSON 数据。它可以在
同一主机或不同主机上
(必须提供 JSONP)。请求
参数“term”被添加到其中
网址。数据本身可以位于
与本地数据格式相同
如上所述。

第三种变化,回调,
提供最大的灵活性,并且可以
用于连接任何数据源
自动完成。回调得到两个
参数:

1) 一个请求对象,有一个
称为“term”的属性,指的是
为当前文本中的值
输入。例如,当用户
进入“新哟”城市领域,
自动完成术语将等于“new yo”。

2) 响应回调,期望
包含数据的单个参数
向用户建议。这个数据
应根据
提供的术语,可以是任何
上面描述的格式很简单
本地数据(字符串数组或
带有标签/值/两者的对象数组
特性)。重要的是当
提供自定义源回调
处理请求期间的错误。你
必须始终调用响应回调
即使您遇到错误。这
确保小部件始终具有
正确的状态。

Look at this demo - it's what you want to do (get data using ajax):

http://jqueryui.com/demos/autocomplete/#remote

You can pull data in from a local
and/or a remote source: Local is good
for small data sets (like an address
book with 50 entries), remote is
necessary for big data sets, like a
database with hundreds or millions of
entries to select from.

Autocomplete can be customized to work
with various data sources, by just
specifying the source option. A data
source can be:

an Array with local data a String,
specifying a URL a Callback The local
data can be a simple Array of Strings,
or it contains Objects for each item
in the array, with either a label or
value property or both. The label
property is displayed in the
suggestion menu. The value will be
inserted into the input element after
the user selected something from the
menu. If just one property is
specified, it will be used for both,
eg. if you provide only
value-properties, the value will also
be used as the label.

When a String is used, the
Autocomplete plugin expects that
string to point to a URL resource that
will return JSON data. It can be on
the same host or on a different one
(must provide JSONP). The request
parameter "term" gets added to that
URL. The data itself can be in the
same format as the local data
described above.

The third variation, the callback,
provides the most flexibility, and can
be used to connect any data source to
Autocomplete. The callback gets two
arguments:

1) A request object, with a single
property called "term", which refers
to the value currently in the text
input. For example, when the user
entered "new yo" in a city field, the
Autocomplete term will equal "new yo".

2) A response callback, which expects
a single argument to contain the data
to suggest to the user. This data
should be filtered based on the
provided term, and can be in any of
the formats described above for simple
local data (String-Array or
Object-Array with label/value/both
properties). It's important when
providing a custom source callback to
handle errors during the request. You
must always call the response callback
even if you encounter an error. This
ensures that the widget always has the
correct state.

嘿看小鸭子会跑 2024-10-15 02:12:23

以下示例展示了如何使用 jQuery UI 自动完成插件指定一个 URL,该 URL 将以 JSON 形式从数据库返回结果。

$("#search_company").autocomplete({
    source: "/Search", // <-- URL of the page you want to do the processing server-side
    minLength: 4 // <-- don't try to run the search until the user enters at least 4 chars
});

自动完成功能会自动将名为“term”的查询字符串参数附加到 URL,因此您的搜索页面需要预料到这一点。不确定您正在使用什么服务器技术,但由于我是一名 .NET 开发人员,这里有一个 ASP.NET MVC 中的示例:)

public ActionResult Search(string term) {
    var results = db.Search(term); // <-- this is where you query your DB
    var jqItems = new List<jQueryUIAutoCompleteItem>();
    foreach (var item in results) {
        jqItems.Add(new jQueryUIAutoCompleteItem() {
            value = item.CompanyId.ToString(),
            id = item.CompanyId.ToString(),
            label = item.CompanyName
        });
    }
    return Json(jqItems.ToArray(), JsonRequestBehavior.AllowGet);
}

jQueryUIAutoCompleteItem 只是一个数据容器,表示自动完成插件所需的 JSON 格式。

public class jQueryUIAutoCompleteItem {
    public string value { get; set; }
    public string label { get; set; }
    public string id { get; set; }
}

Here's an example of how to specify a URL that will return the results from the database as JSON using the jQuery UI autocomplete plugin.

$("#search_company").autocomplete({
    source: "/Search", // <-- URL of the page you want to do the processing server-side
    minLength: 4 // <-- don't try to run the search until the user enters at least 4 chars
});

Autocomplete will automatically append a querystring parameter named "term" to the URL so your search page will need to expect that. Not sure what server technology you're using but since I'm a .NET developer here's an example in ASP.NET MVC :)

public ActionResult Search(string term) {
    var results = db.Search(term); // <-- this is where you query your DB
    var jqItems = new List<jQueryUIAutoCompleteItem>();
    foreach (var item in results) {
        jqItems.Add(new jQueryUIAutoCompleteItem() {
            value = item.CompanyId.ToString(),
            id = item.CompanyId.ToString(),
            label = item.CompanyName
        });
    }
    return Json(jqItems.ToArray(), JsonRequestBehavior.AllowGet);
}

jQueryUIAutoCompleteItem is just a data container that represents the JSON format that the autocomplete plugin expects.

public class jQueryUIAutoCompleteItem {
    public string value { get; set; }
    public string label { get; set; }
    public string id { get; set; }
}
北城孤痞 2024-10-15 02:12:23

您是对的,将整个 60,000 条记录列表发送到客户端的计算机听起来并不是最好的解决方案。您会注意到,与许多其他网站一样,谷歌在其自动完成功能中仅向您显示少数最受欢迎的匹配项。

您可以通过等待用户输入两个或三个字母而不是搜索第一个字母来缩短列表。

您可以在列表中进行页面分块(它有不同的名称)。也就是说,只返回前 10 或 15 个匹配项。用户可以通过滚动或单击“显示更多结果”链接来获取更多列表。当然,您必须为此编写(或搜索)所有 javascript 代码。

You're correct that sending the whole 60,000-record list to the client's machine doesn't sound like the best solution. You'll notice that Google only shows you a handful of the most popular matches in its autocomplete, as to many other websites.

You could shorten the list by waiting for the user to type two or three letters instead of searching on the first one.

You could do page chunking in the list (it goes by various names). That is, only return the top 10 or 15 matches. The user can get more of the list by scrolling or by clicking on a "Show More Results" link. You have to write (or search for) all the javascript code for this, of course.

小嗷兮 2024-10-15 02:12:23

这篇文章可能有点晚了,但对于其他找到它的人来说。我创建了一个 jquery 插件和与 Foursquare 一起使用的 jqueryui 自动完成控件。您可以阅读这篇文章并下载插件 Foursquare自动完成插件

It might be a bit late to this post but for others that find it. I created a plugin for jquery and the jqueryui autocomplete control that works with Foursquare. You can read the post and download the plugin at Foursquare Autocomplete Plugin

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文