jQuery自动完成

时间:2011-04-13 14:17:11

标签: javascript jquery ajax

我正在从数据库中读取我的卡拉OK列表并且运行良好但我想要做的是能够在搜索表单中键入字符串并且当我键入它时开始加载匹配的歌曲和/或艺术家。

我知道我需要什么的基础知识但不确定我需要做什么来自动完成?

任何帮助或资源都将有用

2 个答案:

答案 0 :(得分:0)

以下是jQuery UI自动完成文档:

http://jqueryui.com/autocomplete/

以下是如何实施的示例:

var AutoCompleteOptions = { source: function( request, response ) {
    $.ajax({
        url: 'your URL here',
        dataType: "json",
        data: {
            itemToSearch: request.term // could be any data you are passing in for search
        },
        success: function(data) {
            // do something where search values are returned
        },                                  
    });
    }, 
    select: $.proxy(function(event, ui){
        // what you want to do with that information
        // using a proxy to preserve the reference to 'this'
        return false; // prevent the default response (typically inserting the selected value into the textbox the dropdown is being displayed from.
    },this), 
    open: function(event, ui) { 
        // things to do when the dropdown is rendered
        return false; // prevent default autocomplete open action
    },
    focus: function(event, ui) {
        // what to do when an the user hovers over an item in the drop down
        return false; // prevent default autocomplete open action
    },
    minLength:0 // be sure to set this if you want to be able to trigger the search event manually and have it display results
    };

 var Input = $("input");

 Input.autocomplete(this.AutoCompleteOptions)

答案 1 :(得分:0)

您可以按照应该出现的顺序使用jQuery自动完成,包含库和依赖文件 here is autocomplete

PHP代码

public function cities() {

    $term = $_GET['term'];
    $cities = array("one","two","three");// contains value fetched from DB
    $filtered = array();
    foreach ($cities as $city) {
      if (stripos($city, $term) !== false) {
        array_push($filtered, $city);
      }
    }
    echo json_encode($filtered);
    exit;
  }

jQuery代码

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#textboxid" ).autocomplete({
      source: "cities",
      minLength: 2,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.value + " aka " + ui.item.id :
          "Nothing selected, input was " + this.value );
      }
    });
  });
</script>