我正试图创建一个ajax函数来重新加载<div>
,而不是整个页面。
工作原理:-在输入字段中写入时,div会在每个字符正确后重新加载。
什么不起作用:-当输入字段再次完全为空时,它不会显示我在数据库中的所有条目。
这是我在php文件中的div:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
} }
这是我在搜索中得到的。php
<?php
include 'test/database.php';
$pdo = Database::connect();
if($_GET['game'] == "") {
$sql="SELECT * FROM games WHERE active=1";
echo "<script type='text/javascript'>alert('Should be empty')</script>";
} else {
$q = $_GET['game'];
$sql="SELECT * FROM games WHERE gamenamelong LIKE '%".$q."%'";
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
$gameResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount1 = count($gameResults);
有人能帮我吗?非常感谢。
由于我们不知道您的表单是什么样子的,也不知道是什么调用函数showGames
-how,所以我只能给出一个模糊的答案。但你的主要问题/失误应该通过以下方式解决:
在函数showGames
中,如果搜索字符串为空,则永远不会调用ajax,因此无法返回所有结果。
所以我建议这样改变这个功能:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
//remove that: return;
}
// remove the 'else { '
// now you allways hit the ajax
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
// remove closing bracket of if-else: '}'
}