[英]PHP response using JQuery
我正在嘗試通過PHP類使用自動完成功能。 下面是JQuery。
$(document).ready(function() {
$( ".autocomplete" ).each(function() {
$(this).autocomplete({
source: 'php/LiveSearch.php?name='+ $(this).attr('name') + '&',
minLength: 1,
appendTo: "#container"
});
});
});
我在LiveSearch.php下面創建了從數據庫獲取數據的方法
<?php
interface IConnectInfo {
const HOST = 'XXX.0.0.1:XXXX';
const UNAME = 'root';
const PW = 'xxx';
const DBNAME = 'test';
public static function doConnect();
}
class UniversalConnect implements IConnectInfo{
private static $server=IConnectInfo::HOST;
private static $currentDB=IConnectInfo::DBNAME;
private static $user=IConnectInfo::UNAME;
private static $pass=IConnectInfo::PW;
private static $hookup;
public static function doConnect() {
self::$hookup = mysqli_connect(self::$server, self::$user, self::$pass, self::$currentDB);
if(self::$hookup) {
echo ("Successful connection to MySQL:<br/>");
}
elseif (mysqli_connect_error(self::$hookup)) {
echo ('Here is what is failed: ' .mysqli_connect_error());
}
return self::$hookup;
}
}
class LiveSearch {
private $table;
private $hookup;
private $sql;
private $name = array();
private $res;
private $json;
private $term;
public function __construct() {
$this->table = "master";
//create mysqli object
$this->hookup = UniversalConnect::doConnect();
$this->doDisplay();
$this->hookup->close();
}
public function doDisplay() {
$this->term = 'g';
//$this->term = $_GET['term'];
$this->sql = "SELECT DISTINCT(Asset) FROM $this->table where Business LIKE '%$this->term%'";
try {
$result = $this->hookup->query($this->sql);
while ($row = $result->fetch_assoc()) {
$this->res = $row['Asset'];
array_push($this->name, $this->res);
}
$this->json = json_encode($this->name);
echo $this->json;
$result->close();
}
catch(Exception $e) {
echo "Here's what went wrong: " .$e->getMessage();
}
}
}
$Business1 = new LiveSearch();
?>
當我在網絡瀏覽器上打開LiveSearch.php時,它會為我提供正確的結果。通過從數據庫中獲取數據來提供正確的json輸出。 但是,當我嘗試使用autcomplete搜索時,它不會給出任何結果。 我以為結果不會轉到JQuery,但是當我編寫其他簡單類(如下所示)並創建該類的實例時,結果會顯示在自動完成中。 不知道LiveSearch類中是否缺少任何內容,但是我直接在瀏覽器上得到了LiveSearch.php的結果。 下面是其他正在工作的簡單類
class swapnil {
public function __construct() {
$this->display();
}
public function display() {
$this->name = array("Swapnil");
$this->json = json_encode($this->name);
echo $this->json;
}
}
$Business = new swapnil();
提前致謝。
我認為,如果您創建了一個單獨的函數來從服務器獲取數據的話,它更易讀,例如:
$(this).autocomplete({
source: function(request, response) {
$.getJSON("php/LiveSearch.php", { name: $('#yourInputId').val() }, response);
},
...
}
其次,我認為問題出在返回的JSON上,因為您指出第二次嘗試使用示例數據是可行的。
因此,請使用函數代替字符串作為源(因為它更具可讀性,並且更易於調試)。 之后,您應該調試getJSON源響應並將其格式化以匹配自動完成格式 。
感謝您的所有投入。 我得到了錯誤。 發生這種情況的原因是,在其中一個類中,我還有其他回聲-成功連接到MySQL。 json很難發送整個日期。 我評論了那條線,並且工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.