我有一个网页,允许用户在文本框中输入minGPA来查询数据库并显示符合该条件的学生的所有记录。 html调用一个单独的php文件,还包括调用函数的ajax。我遇到的问题是无论我的查询是什么让所有学生都回归。这困扰了我2天,现在试图找出我的错误。
表格数据:
CREATE DATABASE student_gpa_db;
USE student_gpa_db;
CREATE TABLE student (
studentID INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
GPA DECIMAL(4,2) NOT NULL,
PRIMARY KEY(studentID)
);
INSERT INTO student VALUES
(1, "John Doe", "johndoe@gmail.com", 3.56),
(2, "Jim Smith", "jimsmith@gmail.com", 2.79),
(3, "Jerry Gold", "jerrygold@gmail.com", 3.78),
(4, "Jane Doe", "jandoe@gmail.com", 2.99),
(5, "Jill Hill", "jillhill@gmail.com", 2.55);
PHP / HTML:
<?php
//get user input from text box
require_once('student_gpa_db.php');
//validate user enters a value
$minGPA = filter_input(INPUT_POST, 'minGPA');
//Code for query
$query = 'SELECT *
FROM student
WHERE GPA >= :minGPA
ORDER BY studentID';
$statement = $db->prepare($query);
$statement->bindValue(':minGPA', $minGPA);
$statement->execute();
$students = $statement->fetchAll();
?>
<!--table to hold output-->
<table>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Email</th>
<th>GPA</th>
</tr>
<?php foreach ($students as $student) : ?>
<tr>
<td><?php echo $student['studentID']; ?></td>
<td><?php echo $student['name']; ?></td>
<td><?php echo $student['email']; ?></td>
<td><?php echo $student['GPA']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript">
function queryStudent() {
var ajaxRequest = new XMLHttpRequest;
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
document.getElementById("ajax_output").innerHTML = ajaxRequest.responseText;
}
};
ajaxRequest.open("GET", "gpa_search.php", true);
ajaxRequest.send(null);
}
</script>
<form action="gpa_search.php" method="post" id="form1">
<label>Minimum GPA: </label>
<input type="text" id="GPA" name="minGPA"><br><br>
<input type="button" onclick="queryStudent();" value="Search" id="button">
</form><br>
<p>Students with higher than minimum GPA will be displayed below.</p><br>
<!--output section after search-->
<section id="ajax_output"> <!--Echo the user input variable with output-->
<h3>Student list (Students with GPAs higher than <?php echo htmlspecialchars($minGPA); ?></h3>
</section><br><br>
<a href="search_split.htm">Search & Split</a>
答案 0 :(得分:1)
您应该使用ajax请求传递param。
只需将以下功能替换为您的功能并检查。
function queryStudent() {
var ajaxRequest = new XMLHttpRequest;
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
document.getElementById("ajax_output").innerHTML = ajaxRequest.responseText;
}
};
params = "minGPA=" + document.getElementById("GPA");
ajaxRequest.open("POST", "gpa_search.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}