2014-04-02 90 views
1

我在這裏有自動完成功能的ajax功能。我試圖通過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); 
    } 
} 
?> 

回答

1

在控制檯中,如果你沒有看到任何錯誤,看看反應是什麼。如果響應是空的,請加上:

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

就在echo json_encode($ str);

$ .getJSON要求頭是application/JSON

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); 
+0

@不工作:( – user3462269

+0

@ user3462269什麼問題? – Girish

+0

@autocomplete不工作,那裏沒有數據顯示在文本框中 – user3462269

相關問題