来自URL的jQuery Ui自动完成问题

时间:2013-12-24 00:20:01

标签: jquery ajax json jquery-ui jquery-ui-autocomplete

您能告诉我如何使用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,,但无效!

1 个答案:

答案 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')

中的网址正确无误