你好,我是Ajax和PHP的初学者,如果我的问题是无用或愚蠢的,很抱歉。但我试图做一个实时搜索与ajax,我已经看了一遍又一遍互联网,但没有什么可以帮助我…所以我在这里!:)我有4个文件,一个用于html,一个连接到数据库,一个用于jQuery,最后一个用于php脚本。我用chrome看了看控制台,我可以看到ajax工作,但没有输出,我不知道为什么…我将把下面的代码留给你,并提前表示感谢!也可能有一些法语在代码中,但它只是变量,我将安全连接到数据库以后。再次感谢你。Html:
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP连接数据库:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery: $(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
和PHP中的脚本:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
删除'motclef = '
中的空格var data = 'motclef= ' + recherche;
在你的PHP代码中加上下划线$_GET['motclef_']
(如果你不删除空格的话)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}