Select2过滤器不起作用

时间:2014-10-07 09:15:48

标签: javascript ajax json jquery-select2

我使用Select2来处理我的dropdownmenu。 下拉菜单通过" Ajax-call"填充。到PHP,从Mysql获取数据。

Select2下拉菜单提供搜索功能和过滤功能。 当我在搜索字段中输入内容时,字母会加下划线,但过滤器不起作用。 所以列表不会被我输入的字母过滤掉。为什么?

JS:

$(document).ready(function(){
$("#test").select2({
placeholder: "test",
minimumInputLength: 1,
ajax: {
    url: "test.php",
    dataType: 'json',
    //search term
    data: function (term, page) {
        return {
        q: term, // search term
        page: page
        };
    },
    results: function (data, page) {
    return { results: data};
    } //End of results
}, //End of Ajax
}); //End of select2

1 个答案:

答案 0 :(得分:1)

过滤必须在服务器端完成。 这个PHP脚本将使过滤工作。

PHP:

<?php
// setup databse connection
require_once('db.php'); 

// Select from database, i have set the limit to 40 to speed up results
$result = $db->prepare("SELECT * FROM table WHERE option LIKE :term ORDER BY option ASC LIMIT 0,40");

// bind the value for security with the wildcard % attached.
$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
$result->execute();

// make sure there are some results else a null query will be returned
if($result->rowcount() != 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)){
    $answer[] = array(
                    "id"=>$row['option_id'],
                    "text"=>$row['option']);
// the text I want to show is in the form of option
}
} else {
// 0 results send a message back to say so.
$answer[] = array("id"=>"0","text"=>"No Results Found..");
}

// finally encode the answer to json and send back the result.
echo json_encode($answer);