使用jquery ajax从自动完成中获取结果


get result with jquery ajax from autocomplete

我正在使用jQuery自动完成,并希望从名为some.php的php文件中检索数据,该文件中只写有

<?php
echo "Hello World";
?>

这是javascript

<script type="text/javascript">
$(function(){
    $("#key").autocomplete({
        source: function(){
            $.ajax({
                type: "POST",
                url: "./some.php",
                data: {key: $("#key").val()},
                success: function(result){
                    // what code is needed here to be placed
                }
            });
        }
    });
});
</script>

和html=>

<input type="text" name="key" id="key">

我认为脚本写得正确,因为当我在success function alert(result)中写时,它会得到"Hello world",但我希望它在下拉框中,如何解决这个问题,请帮助我,谢谢:)

$("#key").autocomplete({
    source: function(request, response){
        $.ajax({
            type: "POST",
            url: "./some.php",
            data: {key: request.term},
            success: function(result){
                response(result);
            }
        });
    }
});

response(result)将显示自动完成菜单——result应该是一个项目数组(其中每个项目是一个字符串或一个带有valuelabel键的对象)。

正如SJ-GJ所提到的,您可以简单地设置source: "./some.php",但需要修改some.php以接受请求参数term并返回一个json项目数组。

试试这个:

JS:

<script type="text/javascript">
$(function(){
    $("#key").autocomplete({
        source: "./some.php"
    });
});
</script>

PHP:

$result = array('1' => 'Hello World');
echo json_encode($result);