2015-10-17 75 views
0

我想用自定義數據使用jQuery插件「自動完成」。它在我的代碼中不起作用。與自定義數據的自動完成jquery

ajax調用工作正常,我看到了答覆。但答案並未顯示在頁面上。

的反應是一樣的東西如下:

[{"id_pseudo":12,"nom":"COLLINS","prenom":"Phil","image":"images\/avatar_48x48.png"}] 

我的js代碼是:

$('#rechercher_ami').autocomplete({ 
    source : function(requete, reponse){ 
     $.ajax({ 
      url : $('#url_for_ajax').val() + '/getRechercherAmiAjax', 
      dataType : 'json', 
      data : {ami : $('#rechercher_ami').val(), maxRows : 15}, 
      beforeSend : function() {$('#waiting_autocomplete').show();}, 
      success : function(donnee){ 

       $('#waiting_autocomplete').hide(); 

      } 
     }); 
    }, 
    minLength: 3, 
    delay:500, 

    select: function(event, ui) { 
     alert('hello'); 
     return false; 
     } 
}) 

$('#rechercher_ami').data("ui-autocomplete")._renderItem = function(ul, item) { 
    return $("<li>") 
    .append("<a>" + item.nom + "<br>" + item.prenom + "</a>") 
    .appendTo(ul); 
}; 

什麼是錯的代碼?

回答

1

您應該調用響應回調函數,並以documentation中提及的可接受格式傳遞結果。

例如:

$('#rechercher_ami').autocomplete({ 
    source: function(request, response) { 
    $.ajax({ 
     url: $('#url_for_ajax').val() + '/getRechercherAmiAjax', 
     dataType: 'json', 
     data: { 
     ami: request.term, 
     maxRows: 15 
     }, 
     beforeSend: function() { 
     $('#waiting_autocomplete').show(); 
     }, 
     success: function(data) { 
     $('#waiting_autocomplete').hide(); 
     var result = $.map(data,function(item){ // form the data as you wish 
      return { 
        label:item.nom, 
        value:item.id_pseudo 
       }; 
      }); 
     response(result); // must pass valid data to response call back 
     } 
    }); 
    }, 
    minLength: 3, 
    delay: 500, 

    select: function(event, ui) { 
    alert('hello'); 
    return false; 
    } 
}); 
+0

非常感謝您的幫助,現在它工作。 – Dom