如何在wordpress中实现jquery自动完成器

时间:2013-07-14 15:44:21

标签: php jquery wordpress autocomplete

我正在尝试让自动抱怨在wordpress中工作。

这是我的PHP代码

function autocompleteCallback() {
    global $wpdb; // this is how you get access to the database

    //$whatever = $_POST['search_string'];

    $name=$_POST['search_string'];
   // echo'hiii'. $name='a';
    $employee=$wpdb->get_results("SELECT `user_login` FROM wp_users WHERE user_login LIKE '$name%' ");

    foreach($employee as $key=> $value){
    $myarr[]=array('val' => $value->user_login);
    }

    //wp_reset_query();

    echo json_encode($myarr);

    die(); // this is required to return a proper result
}

add_action('wp_ajax_autocompleteCallback', 'autocompleteCallback');
add_action('wp_ajax_nopriv_autocompleteCallback', 'autocompleteCallback');

这是我的jquery

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

    $("#se").autocomplete({

      //dataType: "json",
      source: function( request, response ) {
                $.ajax({
                    url: './wp-admin/admin-ajax.php',
                    dataType: "json",
                    data: {
                        action: 'autocompleteCallback',
                        search_string:'a',
                       // term: $(options.fieldName).val()
                    },
                    success: function( data ) {
                    //alert(data);
                    alert('huii');
                        response( $.map( data.results, function( item ) {
                            return {
                            alert('hi');
                                label: item.val,
                                ///value: item.title,
                                //url: item.url
                            }
                        }));
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR, textStatus, errorThrown);
                    }
                });
            },
      minLength: 1,
      //select: function( event, ui ) {
      //  log( ui.item ?
      //    "Selected: " + ui.item.value + " aka " + ui.item.id :
     //     "Nothing selected, input was " + this.value );
     // }

     // select: function( event, ui ) {
     //   log( ui.item ?
     //     "Selected: " + ui.item.value + " aka " + ui.item.id :
    //      "Nothing selected, input was " + this.value );
    //  }
    });
});

但是,我可以在普通的html,php网站上进行此工作,我将源代码作为字符串传递。当我使用source标签函数时,我无法弄清楚我在哪里做错了。

html代码

<input id ="se" type="text" name="test" width="20" />

1 个答案:

答案 0 :(得分:0)

为什么你不使用这个很棒的插件:SearchAutocomplete