我在一个返回数学问题的类中有PHP函数:
public function level1() {
//level 1 and 2
//single digit addition and subtraction
//randomly choose addition or subtraction
//1 = addtion, 2 - subtraction
$opperand = rand( 1, 2 );
//if the problem is a subtraction, the program will keep generating problems if a negative problem is generated
//if opperand is a subtraction, do generate both numbers while the answer is negative
if ( $opperand == 2 )
{
do {
//randomly generate first number
$number1 = rand( 1, 9 );
//randomly generate second number
$number2 = rand( 1, 9 );
//compute the answer
$answer = $number1 - $number2;
//change variable to actual opperand
$opperand = "-";
} while ( $answer < 0 );
}
else
{//addition problem
//randomly generate first number
$number1 = rand( 1, 9 );
//randomly generate second number
$number2 = rand( 1, 9 );
//compute the answer
$answer = $number1 + $number2;
//change variable to actual opperand
$opperand = "+";
}//end if/else
return array( $number1 . " " . $opperand . " " . $number2 . " ", $answer );
我从ajaxHandler.php调用此函数(我从ajax调用)
$problemData = $MathEngine->level1();
return $problemData;
php将始终返回一个数组,但我无法弄清楚如何在javascript中操作甚至查看结果作为数组。有没有办法做到这一点?我之前使用过标准的Get ajax调用,所以这不是新的。当我尝试将ajax响应文本作为数组引用时,我什么都没得到(当我点击按钮时)或'undefined'
var problemData = ajaxRequest.responseText;
alert( problemData[0] )
答案 0 :(得分:2)
// php - this will produce a json string
echo json_encode(array( $number1 . " " . $opperand . " " . $number2 . " ", $answer ));
// and in javascript - parse json string to javascript object
var problemData = JSON.parse(ajaxRequest.responseText);
答案 1 :(得分:1)
尝试echo $problemData;
而不是返回它。
致电alert( problemData[0] )
时出现的错误是什么?
ajax只捕获字符串或json对象,所以只有这样才能将此数组作为字符串返回并在js中将其拆分或在php端的该数组上使用json_encode
var data = problemData.split(' ');
alert(data[0]);
答案 2 :(得分:1)
我会使用JSON。如果您之前从未听说过JSON,那么这只是在语言/平台之间来回发送内容的简单方法。
在PHP脚本中,添加此代码段以将数组作为JSON编码文本进行回显。对您的AJAX请求的响应将是您回应的任何内容。
// End of PHP script
$problemData = $MathEngine->level1();
$tmpOut = '{"bind":'. json_encode(array("problemData" => $problemData)) .'}';
echo $tmpOut;
exit;
现在在您的Javascipt中,解码您的JSON字符串。
// Javascript
var jsonObj=eval("("+ajaxRequest.responseText+")");
var problemData = jsonObj.bind.problemData;
答案 3 :(得分:0)
你可以使用json对象从javascript(AJAX)发送和接收数据到php。使用json_encode()来编码来自php的数据,然后以html或文本的形式将其传递给javascript。然后,javascript调用json_decode来检索数据并显示。