【问题标题】:AJAX PHP Server side respond but I can not display the response in client side pageAJAX PHP 服务器端响应,但我无法在客户端页面中显示响应
【发布时间】:2021-02-11 21:48:14
【问题描述】:

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

【问题讨论】:

  • $('#StudentsSelection').append(` &lt;option 反引号是错字吗?
  • 嗨。 $("#Roomnum").append(Student_Name); 是什么,您在输入框中附加值吗?那不应该是.val(Student_Name)
  • @Swati .val(Student_Name) 也不起作用
  • 您好,请检查您的浏览器控制台是否有任何错误?
  • @Swati 现在解决了,谢谢

标签: php jquery ajax


【解决方案1】:

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

【讨论】:

  • 抱歉你的代码没有解决问题 Roomnum 输入没关系,$("#Roomnum").empty(); $("#Roomnum").append(Student_Name);只是为了检查响应
猜你喜欢
  • 2019-12-18
  • 1970-01-01
  • 2021-10-21
  • 2021-03-18
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多