jQuery UI通过URL的JSON自动完成 [英] 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?
我尝试过这样更改source-option:
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=<term>
结尾.
Also notice that the data
parameter passed to the AJAX call should end up as ?query=<term>
when the user types a term.
这篇关于jQuery UI通过URL的JSON自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!