您能告诉我如何使用jQuery UI Autocomplete从URL获取数据吗?目前我有一个代码可以解决我的问题:
var data = [
{"label":"Aragorn", "actor":"Viggo Mortensen"},
{"label":"Arwen", "actor":"Liv Tyler"},
{"label":"Bilbo Baggins", "actor":"Ian Holm"},
{"label":"Boromir", "actor":"Sean Bean"},
{"label":"Frodo Baggins", "actor":"Elijah Wood"},
{"label":"Gandalf", "actor":"Ian McKellen"},
{"label":"Gimli", "actor":"John Rhys-Davies"},
{"label":"Gollum", "actor":"Andy Serkis"},
{"label":"Legolas", "actor":"Orlando Bloom"},
{"label":"Meriadoc Merry Brandybuck", "actor":"Dominic Monaghan"},
{"label":"Peregrin Pippin Took", "actor":"Billy Boyd"},
{"label":"Samwise Gamgee", "actor":"Sean Astin"}
];
$(function() {
$( "#search" ).autocomplete(
{
source:data,
select: function( event, ui ) {
$( "#search" ).val( ui.item.label + " / " + ui.item.actor );
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a><strong>" + item.label + "</strong> / " + item.actor + "</a>" )
.appendTo( ul );
};
});
和HTML:
<input type="text" id="search" />
但是我需要从服务器(data.json.txt)上存储的json文件中获取数据,而不是放在页面上。我尝试将source:data,
更改为source:data.json.txt,
,但无效!
答案 0 :(得分:0)
您可以尝试使用$.get()
来获取数据。
$(function () {
var data;
$.get('data.json.txt', function (response) {
data = response;
$("#search").autocomplete({
source: data,
select: function (event, ui) {
$("#search").val(ui.item.label + " / " + ui.item.actor);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.label + "</strong> / " + item.actor + "</a>")
.appendTo(ul);
};
}, 'json');
});
请确保此处的$.get('/path/to/data.json.txt')
。