自动完成源通过ajax获取

时间:2014-02-25 02:23:11

标签: jquery ajax

我现在正在使用自动完成功能。我需要做的是更改自动完成的来源,我需要连接我的ajax以从数据库中获取值。我如何在我当前的脚本上连接下面这个脚本?请帮助我真的坚持这个。

<script>
$(document).ready(function() {
    var data = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "iran", "Scheme"];
    $("#autocomplete").autocomplete(data, { mustMatch: true });
});
$('input#autocomplete').result(function(event, data, formatted) {
    $("#result").html(!data ? "No match found!" : "Selected: " + formatted);
}).keyup(function() {
    $(this).search();
    $(this).css("background-color", "#D6D6FF");
});
</script>

这是我当前的代码

$( "#tags" ).autocomplete({
source: 'autocomplete.php?'
});
});
function changeAutoComplete (val) {
    $( "#tags" ).autocomplete({
        source: 'autocomplete.php?selected='+val
    });
}

<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value=""  selected="selected">Choose</option>
<?php echo $option; ?>
</select>

自动填充

<?php
    $mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
    $auto = $mysqli->real_escape_string($_GET["term"]);
    $selected = $mysqli->real_escape_string($_GET["selected"]);
    $sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND cat_code='$selected' GROUP BY id ORDER BY item" ); 

    if($sql)
    {
        $str = array();
        while($row=mysqli_fetch_array($sql))
        {
            $str[] = $row['item'];
        }
        echo json_encode($str);
    }
?>

1 个答案:

答案 0 :(得分:0)

尝试改变这个:

function changeAutoComplete (val) {
    $( "#tags" ).autocomplete({
        source: 'autocomplete.php?selected='+val
    });
}

进入这个:

function changeAutoComplete (val) {
    $( "#tags" ).autocomplete("option", "source", "autocomplete.php?selected=" + val);
}

这个想法是你只需要更改为source的{​​{1}}选项,而不是重新初始化整个事物