2010-11-15 43 views
0

我想讓我的輸入字段有jquery自動完成,我從數據庫中獲取公司名稱並將其顯示給用戶。以下是我在jquery.com上找到的一個片段。我想重寫它以適應我的需求,我需要一些幫助。jquery自動完成與遠程json對象

$(function() { 
    function log(message) { 
    $("<div/>").text(message).prependTo("#log"); 
    $("#log").attr("scrollTop", 0); 
    } 

    $("#company_name").autocomplete({ 
    source: function(request, response) { 
    $.ajax({ 
    url: "inc/company_name.php", 
    dataType: "jsonp", 
    data: { 
     featureClass: "P", 
     style: "full", 
     maxRows: 12, 
     name_startsWith: request.term 
    }, 
    success: function(data) { 
     response($.map(data.geonames, function(item) { 
     return { 
     label: item.name, 
     value: item.name 
     } 
     })); 
    } 
    }); 
    }, 
    minLength: 2, 
    select: function(event, ui) { 
    log(ui.item ? 
    "Selected: " + ui.item.label : 
    "Nothing selected, input was " + this.value); 
    }, 
    open: function() { 
    $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); 
    }, 
    close: function() { 
    $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); 
    } 
    }); 
}); 
在源屬性

,在sucess,我要與適當的代碼,以顯示我的JSON對象的數據替換

response($.map(data.geonames, 
    function(item) { ... } 

。下面是我在PHP中創建的json對象。

<?php 
$arr = array ('item' => 'company name'); 
echo json_encode($arr); 
?> 

回答

1

試試自己的自動完成插件:

http://docs.jquery.com/Plugins/autocomplete

爲例:

var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" "); 
    $("#example").autocomplete(data); 

您可以修改它通過使用ajaxloader從類似ARTE,以適應你的:

http://plugins.jquery.com/node/12682

您可以使用此代碼:

/* init the arte engine */ 
$.arte({'ajax_url':'remote_xml_file_url'}).add_action("xml_node", fct); 

/* the function which will be called every tick with the new node */ 
function fct(data){ 
    window.data = data; 
}