Jquery从SQL表中自动完成打开URL

时间:2016-10-22 03:31:18

标签: php jquery

我真的很感谢你对这个的帮助 我正在使用Jquery自动完成功能,我想在搜索完成后打开一个网址。 我的问题是我不知道如何将url列字段从mysql数据库传递到自动完成

这就是我所拥有的

$(function() {
$( "#skills" ).autocomplete({
    source: 'search.php',
    autoFocus: true,
    select: function(event, ui) {
    var url = ui.item.id;
    if(url != '#') {
    location.replace =url;
    }
    },
});

我的php文件

$dbHost = 'xxxxxx';
$dbUsername = 'xxxxxx';
$dbPassword = 'xxxxxx';
$dbName = 'xxxxxx';

//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);

//get search term
$searchTerm = $_GET['term'];

//get matched data from enlaces table
$query = $db->query("SELECT titulo, url FROM enlaces WHERE titulo LIKE '%".$searchTerm."%' ORDER BY titulo ASC");
while ($row = $query->fetch_assoc()) {
    $data[] = $row['titulo'];
    $url[] = $row['url'];

}

//return json data
echo json_encode($data,$url);

非常感谢你!

1 个答案:

答案 0 :(得分:0)

好的我找到了答案

Php从db获取数据并编码为json

$display_json = array();
$json_arr = array();


$user_input = $_GET['term'];

$query = $db->query('SELECT title, url, cat FROM datakeys WHERE title LIKE "%'.$user_input.'%"');

while ($row = $query->fetch_assoc()) {
    $json_arr["id"] = $row['url'];
    $json_arr["value"] = $row['title'];
    $json_arr["label"] = $row['title'];
    $json_arr["category"] = $row['cat'];
    array_push($display_json, $json_arr);
}

echo json_encode($display_json); //encode that search data

JS

$("#autocomplete").autocomplete({
    source: "search.php",
    autoFocus: true,
    select: function(event, ui) {
    var getUrl = ui.item.id;
    if(getUrl != '#') {
    window.open(getUrl);
    }
    },

    html: true, 

    open: function(event, ui) {
    $(".ui-autocomplete").css("z-index", 1000);
    }
});

希望它可以帮助像我这样的人:)