繁体   English   中英

AJAX PHP 服务器端响应,但我无法在客户端页面中显示响应

[英]AJAX PHP Server side respond but I can not display the response in client side page

我有一个页面可以将一些输入数据发送到 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);
 ?>

在像 Json 一样使用它之前尝试解析对 JSON 的 Ajax 响应,我已经尝试过你的代码,它只是一个字符串:

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”输入做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM