使用MySQL自动完成

时间:2015-11-24 20:15:30

标签: javascript php jquery mysql autocomplete

您好我的JSON数据类型有问题。

  

错误:未捕获TypeError:无法使用'in'运算符在4444中搜索'length'

444 - 这是我发送回jquery的数据。

这是我的代码:

JQUERY:

$('.autocomplete').autocomplete({
    minLength:1,
    source: 'http://localhost/instaling/autocomplete.php',
    select:function(evt, ui)
    {
      this.form.city.value = ui.item.german;
    }
});

PHP:

$searchWord = trim(strip_tags($_GET['term']));

$select = mysql_query("SELECT * FROM `words` WHERE `polish` LIKE '%$searchWord%'");

while ($row = mysql_fetch_array($select)) {
  $german = $row['german'];    
}

echo json_encode($german);

代码有什么问题?我在php中使用encode将数据作为JSON发送到jquery。

1 个答案:

答案 0 :(得分:0)

    define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');
require_once "inc/db.php";
if (isset($_GET['term'])){
$term=$_GET['term'];
    $return_arr = array();
    try {
        $conn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT * FROM `words` WHERE `polish` LIKE '%$searchWord%'");       
       $stmt->execute(array('term' => '%'.$_GET['term'].'%'));
        while($row = $stmt->fetch()) {
            $return_arr[] =  $row['german'];
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    /* Toss back results as json encoded array. */
    echo json_encode($return_arr);
}