jQueryUI autocomplete - when no results are returned

前端 未结 3 809
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 11:19

I\'m wondering how one can catch and add a custom handler when empty results are returned from the server when using jQueryUI autocomplete.

There seem to be a few questio

3条回答
  •  抹茶落季
    2021-02-19 11:48

    Considering source as php script:

    what i did in my code is I returned NO results message from php script like

    $ArrayMe =  Array();
    if(rows found){
      array_push( $ArrayMe ,array('key1'=> $val1, 'key2'=> $val2, 'key3'=> $val3));
    } else {
     array_push( $ArrayMe ,array("message"=>"No results found" ));
    }
    echo json_encode($ArrayMe);
    

    from jquery:

     $( "input#val1" ).autocomplete({
            minLength: 2,
    
            source:function (request, response) {
            $.ajax({
                    type: 'get',
                    url: "path/to/phpscript.php",
                    dataType: "json",
                    data: { term: request.term },
                    success: function(data) {
                            response($.map(data, function (value) {
                                if(value.message){
                                    console.log(value.message);
                                    $('p#val2').html("");
                                    $('p#val3').html("");
                                    return {Message: value.message}
                               } else {
                                    return {
                                        key1: value.val1,
                                        key2: value.val2,
                                        key3: value.val3
    
                                    }
                               }
                            }));
                        }   
                    });
       },  
            focus: function( event, ui ) {
                $( "input#val1" ).val( ui.item.val1);
                $( "p#val2" ).html( ui.item.val2);
                $( "p#val2" ).html( ui.item.val3);
                return false;
            },
            select: function( event, ui ) {
                $( "input#val1" ).val( ui.item.val1);
    
                $( "p#val2" ).html( ui.item.val2);
                $( "p#val3" ).html( ui.item.val3);
    
    
                return false;
            }
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {
            if(item.Message){
                return $( "
  • " ) .append( "
    " + item.Message +"
    " ) .appendTo( ul ); } else{ return $( "
  • " ) .append( "
    " + item.val1+ " | " + item.val2+ " | " + item.val3+"
    " ) .appendTo( ul ); } };
  • . It worked perfectly fine for me.

    If no data gets message as well as triggers required fields.

    I am very poor in explanation so i posted entire code to make it easier.

提交回复
热议问题