我的JSON是这样的
var data = [{"code":"1162","format":"Subscription","name":"Picture Manager ","action":"202"},
{"code" : "1094","format":"Store","name":"Listing Designer","action":"168"},
{"code" : "1407","format":"Subscription","name":"MOTOR_PACKAGE","action":"403"},
{"code" : "1024","format":"Fixed Price","Name":"Picture","action":"120"},
{"code" : "1051","format":"Auction","name":"Gallery Days","action":"49"},
{"code" : "5059","format":"Lead Generation","name":"Scheduled Listings","action":"160"}];
我能够创建一个建议功能,例如
jQuery
$(document).ready(function(){
serverurl = "getJson";
$.getJSON( serverurl, function(data) {
$("#feeCode").autocomplete({
source: function (request, response) {
response($.map(data, function(v,i){
return {
label: v.format+' / '+v.name+' ('+v.code+')' ,
value: v.format+' / '+v.name+' ('+v.code+')'
};
}));
}
});
});
});
HTML
<input class="catinputbox" type="text" id="feeCode" >
它会显示这样的建议
Auction / Gallery Days (1051)
Fixed Price / Picture (1024)
但它不是搜索建议是静态的模式。我想搜索他提供的字符串并给出适当的建议。例如,如果他输入“固定”,则建议应为“固定价格/图片 (1024)”,或者如果他输入“天数”或“1051”,则建议应为“拍卖/画廊天数 (1051)”。
我以前从未使用过自动完成功能,所以如果有人可以解释一下自动完成、请求、响应和搜索。这对我很有帮助
最佳答案
你已经很接近了,只需进行一些调整:
$(document).ready(function() {
serverurl = "getJson";
$.getJSON(serverurl, function(data) {
/* When the response comes back, create an array of objects that the
* autocomplete widget can use, using `$.map`:
*/
var autocompleteData = $.map(data, function(v, i) {
return {
label: v.format+' / '+v.name+' ('+v.code+')' ,
value: v.format+' / '+v.name+' ('+v.code+')'
};
});
/* Initialize the autocomplete widget with the prepared data: */
$("#feeCode").autocomplete({
source: autocompleteData
});
});
});
示例: http://jsfiddle.net/fny66zkd/
在这种情况下,您不需要向 source
参数提供函数。如果您想要执行自定义 AJAX 请求或某种其他类型的自定义过滤功能,则可以执行此操作。
您的代码之前无法正常工作,因为当您向 source
参数提供函数时,您实际上是在告诉小部件您想要进行过滤。
I have never used the autocomplete before so if any one can explain me autocomplete, request, response and search. That will be very helpful for me
source
选项可以提供回调函数(或字符串或数组)。该函数接受两个参数:request
和response
。request
是一个包含有关用户键入内容的信息的对象。您可以通过访问request.term
来访问他们输入的内容。response
是 jQueryUI 传递给您的函数的回调函数。当您准备好向小部件通知要向用户显示的结果集时,可以调用此函数。- 更多信息请参阅 official documentation .
search
方法手动调用自动完成小部件的搜索功能。同样,更多信息可在 official documentation 中找到。 .
关于javascript - JSON 的 jQuery 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388813/