dongliang2005 2017-04-17 13:42
浏览 60
已采纳

简单的Ajax自动完成示例,无法使用PHP

I saw a video on youtube that did exactly what I try here. I cannot get it to work. This is what I am using: https://www.devbridge.com/sourcery/components/jquery-autocomplete/

I have put all the files under the project folders directly and tried this:

<html>
<head>
<script src="jquery-3.2.1.js"></script>
<script src="jquery.autocomplete.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Autocomplete Input</h1>
<input type="text" id="autocomplete"/>

<script>
$('#autocomplete').autocomplete({
    serviceUrl: '/search.php'
});
</script>
</body>
</html>

and search.php is

<?php
echo json_encode(
    array(
        'suggestions' => array(
            'United Arab Emirates',
            'United Kingdom',
            'United States'
        )
    )
);
?>

Simple as it gets, but can't seem to work. I really tried to make this work, if someone could take a look. The styling is correct, the functionality isn't where. Im typing in words starting whit "Un.." and nothing happens.

  • 写回答

1条回答 默认 最新

  • dougao1106 2017-04-17 13:48
    关注

    From the webpage you linked: https://www.devbridge.com/sourcery/components/jquery-autocomplete/#jquery-autocomplete-response-format

    The response needs to be JSON. If you're echo'ing it yourself, you need to write it as a valid object (note the { and }):

    echo '{ "suggestions": ["United Arab Emirates", "United Kingdom", "United States"] }';
    

    Better would be to let PHP handle the JSON formatting:

    echo json_encode(
        array(
            'suggestions' => array(
                'United Arab Emirates',
                'United Kingdom',
                'United States'
            )
        )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集