这是index.php。当我给出一个输入时,它会获取特定的名称和年份。没关系。但是当我提交表单时,没有任何输入它给出了电影的所有名称和年份,但我不想要这样,用户无法显示保存在数据库中的所有数据。我给了priventdefault()方法,但它不起作用。我怎么解决这个问题 ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///这是query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
答案 0 :(得分:3)
仅当$ name不为空时才执行查询。
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
答案 1 :(得分:1)
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
在javascript中
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
答案 2 :(得分:0)
在query.php中,如果为空,请始终将空字符串分配给行中的$name
&#39; name&#39;值传递给query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
因此,查询将返回db中的所有结果,因为$name
是一个空字符串,并与db中的所有数据匹配。
您可以验证$ name是否为空,而不是运行查询。