2014-02-27 56 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对象从服务器返回的响应,标签和值返回到自动完成文本框。

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