使用来自 URL 的 JSON 的 jQuery UI 自动完成 [英] jQuery UI autocomplete with JSON from URL
问题描述
我正在使用 jQuery UI 自动完成功能.我可以使用 jQuery UI 提供的示例使其工作,如下所示:
I'm using the jQuery UI Autocomplete function. I can make it work with the example provided with jQuery UI like this:
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
});
这没有任何问题.但我需要使用 JSON 作为我的数据源,可以像这样检索:http://mysite.local/services/suggest.ashx?query=ball
This works without any problems. But I need to use JSON as my data source who can be retrieved like this: http://mysite.local/services/suggest.ashx?query=ball
如果我要去那个 URL,我会像这样返回 JSON:
If I'm going to that URL I get JSON back like this:
[{"id":12,"phrase":"Ball"},{"id":16,"phrase":"Football"},{"id":17,"phrase":"Softball"}]
如何使用我的 URL 作为数据源?
How can I use my URL as the data source?
我试过像这样更改源选项:
I've tried changing the source-option like this:
$("#tags").autocomplete({
source: "http://mysite.local/services/suggest.ashx"
});
但这无济于事.我猜服务不知道在输入字段中输入了哪个关键字?
But it doesn't help. I guess that the service doesn't know which keyword has been typed in the input field or so?
任何指针都会很棒.
推荐答案
您需要更改源以满足以下规范(在 文档 用于小部件).源必须是一个包含(或返回一个包含)的数组:
You need to change your source to meet the following specifications (outlined in the documentation for the widget). The source must be an array containing (or return an array containing):
- 简单的字符串,或者:
- 包含
label
属性、value
属性或两者的对象.
- Simple strings, or:
- objects containing a
label
property, avalue
property, or both.
如果由于某种原因您无法更改远程源返回的内容,您可以在数据成功检索后对其进行转换.这样做的方法如下:
If for some reason you cannot change what your remote source is returning, you can transform the data once it has successfully retrieved. Here's how you would do that:
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://mysite.local/services/suggest.ashx",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.phrase,
id: el.id
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
});
如您所见,您需要通过将函数传递给小部件的 source
选项来自行调用 AJAX.
As you can see, you'll need to make the AJAX call yourself by passing in a function to the source
option of the widget.
这个想法是使用 $.map
来转换你的将数组转换为包含自动完成小部件可以解析的元素的数组.
The idea is to use $.map
to transform your array into an array that contains elements that the autocomplete widget can parse.
另请注意,当用户键入一个术语时,传递给 AJAX 调用的 data
参数应以 ?query=
结尾.
Also notice that the data
parameter passed to the AJAX call should end up as ?query=<term>
when the user types a term.
这篇关于使用来自 URL 的 JSON 的 jQuery UI 自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!