php - 如何根据 php ajax 请求中的第一个下拉列表在下拉列表中获取记录
问题描述
即使 onchange 功能似乎正在工作,Php ajax 请求也不起作用。
最初 get_data.php 位于与父文件夹不同的文件夹中。我将它移到同一个文件夹但仍然无法正常工作。
//html select option
<select name="slct" id="slct1">
<option selected disabled>----Choose Class ----</option>
<?php
$query = "SELECT * FROM classes ";
//GET RESULT
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()){
?>
<option value="<?php echo $row['class_name']?>"><?php echo $row['class_name']?></option>
<?php
}
?>
<select name="slct" id="slct2" >
<option selected disabled>----Select Student----</option>
</select>
//ajax request
<script type="text/javascript">
$(document).ready(function(){
$('#slct1').on('change',function(){
var StudentID = $(this).val();
if(StudentID){
$.ajax({
type:'POST',
url:'get_data.php',
data:'class_name='+StudentID,
success:function(html){
$('#slct2').html(html);
}
});
}else{
$('#slct2').html('<option value="">Select Class First</option>');
}
});
});
</script>
//get_data.php
<?php
//Include the database configuration file
include '../config/dbconfig.php';
if(isset($_POST["class_name"])){
//Fetch all state data
$query = "SELECT * FROM students WHERE class = ".$_POST['class_name']." ORDER BY id ASC";
//Count total number of rows
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
$rowCount = $result->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select Student</option>';
while($row = $result->fetch()){
echo '<option value="'.$row['class'].'">'.$row['firstname']. $row['middlename'] . $row['lastname']. '</option>';
}
}else{
echo '<option value="">No Student Registered</option>';
}
}
?>
我想在选择课程时在第二个选择选项中获取学生记录。
解决方案
如评论中所述 - 看起来问题可能是由于 SQL 查询中 POST 变量周围缺少引号引起的。如果您使用 a 并将 POST 变量绑定到占位符,这将不是问题prepared statement
- 额外的好处当然是更好地防止 SQL 注入。
<?php
if( isset( $_POST['class_name'] ) ){
include '../config/dbconfig.php';
$sql = 'select * from `students` where `class` = :classname order by id asc';
$args = array(
':classname' => $_POST['class_name']
);
$stmt=$pdo->prepare( $sql );
if( $stmt ){
$result=$stmt->execute( $args );
if( $result && $stmt->rowCount() > 0 ){
echo '<option selected hidden disabled>Select student';
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
printf('<option value='%s'>%s %s %s', $rs->class, $rs->firstname, $rs->middlename, $rs->lastname );
}
} else {
echo '<option selected hidden disabled>No student registered';
}
} else {
exit( '<option selected hidden disabled>error' );
}
}
?>
推荐阅读
- c++ - 无法解释以下 C++ 代码段的输出
- jenkins - Jenkins:从主服务器上的构建文件夹复制到从服务器上的工作区
- javascript - 对浏览器的同源策略感到困惑
- angular - 当 api 位于不同域时,如何通过 Angular Service Worker 缓存 Api 响应
- c++ - Cmake 找不到 -lboost_system
- javascript - 无法在反应原生地图中移动按钮
- android - Gradle 同步失败:无法将具有类“java.io.File”的对象“.../classes/test/release”转换为类“org.gradle.api.file.FileCollection”
- sql-server - 查询优化(IN 与等于)
- firebase - firebase 的 can firestore 和 cloud storage 有什么区别?
- java - 将集合转换为 JSON 并使用 mqtt 发送