gpt4 book ai didi

javascript - 对 jQuery 的自动完成结果进行排序

转载 作者:行者123 更新时间:2023-12-02 15:51:30 25 4
gpt4 key购买 nike

我有一个链接到我的数据库的工作自动完成脚本,但我知道如何对结果进行排序。

我的表有 4 列:ID、位置、slug、人口。该表本身大约有 1,000 个条目。

目前,我的自动完成功能接受用户搜索 slug,并且它会搜索 slug,但我希望自动完成列表结果按人口顺序排序,人口较多的人在列表中排名最高。

索引.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete using PHP/MySQL and jQuery</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>


<body>
<div class="container">
<div class="header">

</div><!-- header -->
<h1 class="main_title">Autocomplete using PHP/MySQL and jQuery</h1>
<div class="content">
<form>
<div class="label_div">Type a keyword : </div>
<div class="input_container">
<input type="text" id="slug" onkeyup="autocomplet2()">
<ul id="list_id"></ul>
</div>
</form>
</div><!-- content -->
<div class="footer">
Powered by Jason's Fingers</a>
</div><!-- footer -->
</div><!-- container -->
</body>
</html>

脚本.js:

// autocomplete : this function will be executed every time we change the text
function autocomplet2() {
var min_length = 3; // min caracters to display the autocomplete
var keyword = $('#slug').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#list_id').show();
$('#list_id').html(data);
}
});
} else {
$('#list_id').hide();
}
}

// set_item : this function will be executed when we select an item
function set_item(item) {
// Changes input to the full name on selecting
$('#slug').val(item);
// Hides list after selection from list
$('#list_id').hide();
}

ajax_refresh.php:

<?php
// PDO connect *********



function connect() {
return new PDO('mysql:host=localhost;dbname=wallettest', 'root', 'butthead', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}

$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM population WHERE slug LIKE (:keyword) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$slug = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['slug']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['slug']).'\')">'.$slug.'</li>';
}


?>

最佳答案

您可以将 $sql 的“ORDER BY”部分设置为:

...ORDER BY population DESC LIMIT 0, 10"

关于javascript - 对 jQuery 的自动完成结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31816939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com