参考下面附带的代码,我希望在我的index.php文件中引用已在processUsersAnswers.php中初始化的变量。
index.php
中的代码段<script type="text/javascript">
function checkAnswers(){
var xhr = new XMLHttpRequest();
/* code */
xhr.open("POST", "processUsersAnswers.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
/* code */
}
}
xhr.send(vars); //
}
processUsersAnswers.php
中的代码段<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
/*How can I retrieve $userAnswers in my index.php file? */
?>
例如,如何在index.php文件中检索$ score的值?
答案 0 :(得分:0)
试试这个:
您的新processUsersAnswers.php
文件
<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
echo json_encode('score' => $score);
exit;
在你的JS中:
<script type="text/javascript">
function checkAnswers(){
var xhr = new XMLHttpRequest();
/* code */
xhr.open("POST", "processUsersAnswers.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
alert(json.score);
}
}
xhr.send(vars); //
}
这不是强制使用JSON,但这样您就可以轻松地从服务器添加更多信息。