自动填充功能不适用于ajax

时间:2014-04-02 05:27:48

标签: ajax autocomplete

我在这里使用ajax函数自动完成脚本。我试图通过ajax从数据库中获取数据,但为什么还没有工作?

以下是我的代码..任何帮助都会感激!

Html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
  $(function() {
    $( "#tags" ).autocomplete({
    source: function(request, response) {
    $.getJSON("autocomplete.php", { app_cn: request.term }, response);
  }
    });
  });
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>

Autocomplete.php

<?php
    include('connect1.php');
if(isset($_GET["app_cn"])) {
    $auto = $mysqli1->real_escape_string($_GET["app_cn"]);
    //$selected = $mysqli1->real_escape_string($_GET["selected"]);

    $sql = $mysqli1->query("SELECT id,item FROM code WHERE item LIKE '%$auto%' GROUP BY item ORDER BY id"); 

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

2 个答案:

答案 0 :(得分:1)

如果您没有看到任何错误,请在控制台中

查看响应内容。如果响应为空,请添加:

header('Content-Type: application/json'); 

就在echo json_encode($ str)之前;

$ .getJSON要求标题为application / json

答案 1 :(得分:1)

你应该在$.getJSON中使用成功回调函数,并传递给响应变量试试这段代码

<script>
  $(function() {
    $( "#tags" ).autocomplete({
    source: function(request, response) {
       $.getJSON("autocomplete.php", { app_cn: request.term }, function(data){
         response(data);
      });
    }
    });
  });
</script>

和PHP脚本

 $str = array();
    while($row = $sql->fetch_assoc())
    {
            array_push($str, array(
                "id" => $row['id'],
                "label" => $row['item'],
                "value" => $row['item']
            ));
   }
   header("Content-type: text/json");
   echo json_encode($str);