我有一个dynamicaly php页面,它显示来自数据库的所有结果,我想创建一个搜索栏,在用户输入的每个字符处更新。我的问题是我不能更新查询!他总是毫无结果。首先,我将查询与表单放在同一个页面中,但这不起作用,因为当我在参数中使用该url时,ajax将运行页面中的所有代码,所以我拆分了所有内容,但仍然不起作用。有什么建议吗?
php页面-与搜索栏-->categorias.php一起使用:
<div class="container">
<h2 class="title">Empresas De Confianza</h2>
<div class="col-lg-12">
<div class="col-lg-6 col-centered">
<form method="POST" action="buscador.php" id="search">
<input class="search-bar" type="text" name="filterName" id="filterName">
<button type="submit" hidden></button>
<?php
$msqliquery = "SELECT * FROM empresa WHERE categorias_id = $id AND menulogo IS NOT NULL";
$array = $connection->query($msqliquery);
?>
</form>
</div>
</div>
<?php
echo '<div class="row index-margin" id="results">';
if (mysqli_num_rows($array) == 0) {
echo "<h2 class='text-center'>No hemos encontrado ningún resultado con esa busqueda!</h2><ul class='text-center'><li class='list-categorias'><a class='fa-categorias fa fa-refresh' href='categorias.php?id=$id'></a></li></ul>";
};
while ($field = mysqli_fetch_array($array)) {
?>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3 parent size">
<a style="background-color:<?php echo $field['color'] ?>"
href="profile.php?id=<?php echo $field['id'] ?>">
<img src="/test<?php echo $field['menulogo'] ?>" class="logo img-grayscale">
<div class="hover-item"><h5 class="label-profile"><?php echo $field['nombre'] ?></h5></div>
</a>
</div>
<?php }
echo '</div>' ?>
´ 表单/搜索栏处理-->buscador.php:
<?php
require 'config.php';
$connection = new mysqli($servername, $username, $password, $db);
session_start();
$id = $_SESSION['id'];
$filterName = $_POST['filterName'];
$msqliquery = "SELECT * FROM empresa WHERE categorias_id = $id AND menulogo
IS NOT NULL AND nombre COLLATE UTF8_GENERAL_CI LIKE '%$filterName%'";
$array = $connection->query($msqliquery);
用于在每个字符和ajax表单提交时更新的函数:
$(document).ready(function () {
var timeoutID = null;
$('#filterName').keyup(function (e) {
clearTimeout(timeoutID);
timeoutID = setTimeout(searchEmpresa.bind(undefined, e.target.value), 500);
});
function searchEmpresa(str) {
console.log('search: ' + str);
$("#search").submit(function (event) {
$.ajax({
method: "POST",
url: 'buscador.php',
data: $("#filterName").val(),
success: function (data) {
console.log(data);
$("#results").load("categorias.php #results > *");
}
});
event.preventDefault();
});
}
})
1条答案
按热度按时间juzqafwq1#
必须将数据作为具有键值对的对象发送
另外你也要纠正方法:“发帖”,所以你应该有发帖的方法而不是发帖的类型,希望它能帮到你。
将此代码放在buscador.php中
并将其附加到具有id result的div中
$('#result')。追加(数据);