【问题标题】:autocomplete jquery with custom data使用自定义数据自动完成 jquery
【发布时间】:2015-10-17 09:05:53
【问题描述】:

我正在尝试使用带有自定义数据的 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 );
}; 

这段代码有什么问题?

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-autocomplete


    【解决方案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;
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 2013-12-11
      相关资源
      最近更新 更多