2014-02-27 58 views
0

我創造了這個jQuery的自動完成,但結果返回[]。 在用戶表中有2個字段:「ID」(int autoincrement)和「名稱(varchar)」,並被填充。自動完成的jQuery mysql數據庫的數據

auto_complete_jquery.html:

<html> 
<head> 
    <title><!-- Insert your title here --></title> 
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> 
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> 
</head> 
<script> 
$(function() { 
$("#tags").autocomplete({source: "name.php", dataType: 'json'}); 
}); 
</script> 
</head> 
<body> 
<div class="ui-widget"> 
<label for="tags">Tags: </label> 
<input id="tags"> 
</div> 
</body> 
</html> 

connection.php:

<?php 
    $hostname="localhost"; 
    $username="root"; 
    $password=""; 
    $conn=mysql_connect($hostname,$username,$password); 
     $dbs = mysql_select_db("jquery_test",$conn); 
    if(!$conn) 
    { 
     echo("Error connection MySQL."); 
     exit(); 
    } 
?> 

name.php:

<?php 
    $return_arr = array(); 
    $term = $_GET["term"]; 
    include "connection.php"; 
    $result= mysql_query("SELECT * FROM users WHERE MATCH(Name) AGAINST('".$term."*')") or die (mysql_error()); 
    ?> 
      <?php 

      while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
      { 
       $row_array['value'] = $row['tagName']; 
       array_push($return_arr,$row_array); 
      } 

      mysql_close($conn); 
      $json=json_encode($return_arr); 
      echo $json; 
      ?> 
+0

你檢查,如果該文件是由瀏覽器查詢和具有正確的內容是什麼? – Tobi

+0

首先,不使用mysql_方法,它們已被棄用,使用庫MySQLi而不是http://uk1.php.net/manual/en/book.mysqli.php,其次爲什麼不嘗試使用'SELECT * FROM用戶WHERE'名'LIKE「%?%」' –

+0

完美!我使用了LIKE運算符,它工作。謝謝! – CleverBall

回答

0

希望你找這個,

$("#PopulateData").autocomplete({ 
      minLength:2, 
      delay: 50, 
      selectFirst: true, 
      open: function() { 
       $(this).data("autocomplete").menu.element.width(409); 
      }, 
      source:function(request,response){ 
      removeConflict.ajax({ 
        url: 'remotefile.php?list='+$('#PopulateData').val(), 
        data: request, 
        dataType: null, 
        type: "GET", 
        success: function(data){ 
        var listarray= jQuery.parseJSON(data); 
        response(
        $.map(listarray, function(item) { 
         var text = item.jsonpropertyA; 
         var code = item.jsonpropertyb; 
         console.log(text) 
         return { 
          label: code, 
          value: text 

         } 
        }) 
        )}, 
       error:function(data){ 
        console.log(data) 
        } 
      }); 
      }, 
      select: function(event, ui) { 
      console.log('value:'+ ui.item.value + ',label:'+ui.item.label); 
     } 
    }); 

JSON對象從服務器返回的響應,標籤和值返回到自動完成文本框。

注意:如果您可以做一些修改,其中五星級的。 :)