如何将PHP文件中的多个值回显到Javascript Ajax调用?
参考下面附带的代码,我希望在index.php文件中引用在processUsersAnswers.php中初始化的变量 index.php中的代码片段如何将PHP文件中的多个值回显到Javascript Ajax调用?,javascript,php,ajax,Javascript,Php,Ajax,参考下面附带的代码,我希望在index.php文件中引用在processUsersAnswers.php中初始化的变量 index.php中的代码片段 <script type="text/javascript"> function checkAnswers(){ var xhr = new XMLHttpRequest(); /* code */ xhr.open("POST", "processUsersAnswers.php", true);
<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); //
}
<?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? */
?>
函数checkAnswers(){
var xhr=new XMLHttpRequest();
/*代码*/
open(“POST”,“processUsersAnswers.php”,true);
setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
xhr.onreadystatechange=函数(){
如果(xhr.readyState==4&&xhr.status==200){
/*代码*/
}
}
xhr.send(变量);//
}
processUsersAnswers.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); //
}
<?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的值?试试以下方法:
新的processUsersAnswers.php
文件
<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
echo json_encode('score' => $score);
exit;
试试这个:
新的processUsersAnswers.php
文件
<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
echo json_encode('score' => $score);
exit;
使用simpleecho
尝试:echo$score
但变量很多。你能说清楚一点吗。你解决问题了吗?是的,我用逗号分隔了元素,然后创建了一个函数,将字符串解释为数组。谢谢。使用simpleecho
试试:echo$score
但是变量很多。你能说清楚一点吗。你解决问题了吗?是的,我用逗号分隔了元素,然后创建了一个函数,将字符串解释为数组。谢谢