简体   繁体   中英

autocomplete jquery with custom data

I am trying to use the jQuery plugin "autocomplete" with custom data. It does not work in my code.

The ajax call works fine, I see the response. But the answer is not displayed on the page.

The response is something like following :

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

My js code is :

$('#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 );
}; 

What's wrong on this code?

You should call the response callback and pass the result in an accepted format mentioned in the documentation .

For example:

$('#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;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM