我有一个页面可以将一些输入数据发送到php页面,稍后应该重新发送响应,稍后服务器端的一些数据应该显示在客户端页面上。
我跟踪了请求,响应如下:6 [{“ Student_Id”:“ 21”,“ Student_Name”:“ Smith”}]
但是我无法在客户端页面上显示结果
HTML脚本
<input type="text" name="Roomnum" id="Roomnum"> </input>
<select id="StudentsSelection" name="Student_Id" style="width:200px;height: 40px;">
<option value="0">- Select -</option>
</select>
Ajax脚本
var Room_Id = $("#Roomnum").val();
$.ajax({
url: 'getStudents.php',
type: 'post',
data: {Room_Id:Room_Id},
dataType: 'json',
success:function(response){
console.log("success");
console.log(response);
var len = response.length;
$("#StudentsSelection").empty();
for( var i = 0; i<len; i++){
var Student_Id = response[i]['Student_Id'];
var Student_Name = response[i]['Student_Name'];
$("#Roomnum").empty();
$("#Roomnum").append(Student_Name);
$('#StudentsSelection').append(`<option value="${Student_Id}">
${Student_Id}-${Student_Name}
</option>`);
}
}
});
PHP脚本
<?php
include "database_connection.php";
$Room_Id= $_POST['Room_Id'];
echo $Room_Id;
$stmt = $connection->query("SELECT * FROM students WHERE Room_Id = '.$Room_Id.' ");
$students_arr = array();
while ($row = $stmt->fetch())
{
$Student_Id = $row['Student_Id'];
$Student_Name = $row['Student_Name'];
$students_arr[] = array("Student_Id" => $Student_Id, "Student_Name" => $Student_Name);
}
echo json_encode($students_arr);
?>
答案 0 :(得分:0)
尝试像Json一样使用Ajax解析JSON之前,我已经尝试了您的代码,它只是一个字符串:
var Room_Id = $("#Roomnum").val();
$.ajax({
url: 'getStudents.php',
type: 'post',
data: {Room_Id:Room_Id},
dataType: 'json',
success:function(response){
response = JSON.parse(response);
console.log("success");
console.log(response);
var len = response.length;
$("#StudentsSelection").empty();
for( var i = 0; i<len; i++){
var Student_Id = response[i]['Student_Id'];
var Student_Name = response[i]['Student_Name'];
$("#Roomnum").empty();
$("#Roomnum").append(Student_Name);
$('#StudentsSelection').append(`<option value="${Student_Id}">
${Student_Id}-${Student_Name}
</option>`);
}
}
});
这应该可以解决您有关响应的问题,但是我不知道您打算如何处理“ Roomnum”输入。