我正在尝试通过POST将所选考试的JSON发送到take_exam.php页面,以便take_exam.php可以为学生显示考试。
exams.php文件包含检查列表。学生可以选择参加考试。我目前正在向take_exam.php发送一个{action:"get_exam",exam:"exam_name“}的JSON,以便它可以为学生显示考试。
用于向take_exam.php发送帖子数据的JavaScript代码
var btns =document.getElementsByClassName("stu-take-test")
for (var i =0; i < btns.length; i++){
btns[i].addEventListener("click", function(){
var obj = new Object;
obj.action = "get_exam";
obj.exam = this.id;
str_json = JSON.stringify(obj);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
location.replace("take_exam.php")
}
};
xhttp.open("POST", "take_exam.php", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(str_json);
});
}
PHP代码的take_exam.php抓取通过ajax发送的JSON,只是为了测试,我正在尝试打印收到的JSON。将来,该文件将与数据库通信,为学生加载测试。但看起来该文件没有收到任何内容:
<?php
$real_json = file_get_contents('php://input');
$decoded_json = json_decode($real_json);
print_r($decoded_json);
Ajax用take_test.php替换exam.php,让学生参加选定的考试
发布于 2018-10-15 07:59:19
这是因为您在成功后将XHR (readyState == 4和status == 200)重定向到相同的脚本,而没有有效负载。尝试对location.replace("take_exam.php")
进行注释,看看会发生什么。
但您可能需要检查$decoded_json
是否为stdClass
(即json已接收并解码),并将结果记录到控制台:
<?php
$real_json = file_get_contents('php://input');
$decoded_json = json_decode($real_json);
if($decoded_json instanceof stdClass) {
// do somethong
var_dump($decoded_json);
// and die maybe =)
die();
}
在JS中:
if (this.readyState == 4 && this.status == 200) {
// location.replace("test.php")
// do something with response
console.log(this.response);
}
更新
将其保存在一个PHP文件中(假设是test.php,因为是xhttp.open("POST", "test.php", true);
),然后在浏览器中打开。
<?php
$real_json = file_get_contents('php://input');
$decoded_json = json_decode($real_json);
if($decoded_json instanceof stdClass) {
var_dump($decoded_json);
die();
}
?>
<button class="stu-take-test" id="math">Math</button>
<div id="response_container"></div>
<script>
var btns =document.getElementsByClassName("stu-take-test")
for (var i =0; i < btns.length; i++){
btns[i].addEventListener("click", function(){
var obj = new Object;
obj.action = "get_exam";
obj.exam = this.id;
str_json = JSON.stringify(obj);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('response_container').innerHTML = this.response;
}
};
xhttp.open("POST", "test.php", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(str_json);
});
}
</script>
https://stackoverflow.com/questions/52808033
复制相似问题