gpt4 book ai didi

PHP 将数组返回给 JavaScript Ajax 调用

转载 作者:行者123 更新时间:2023-11-28 16:09:30 24 4
gpt4 key购买 nike

我在一个类中有 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 响应文本引用为数组时,我要么什么也得不到(当我单击按钮时),要么“未定义”

           var problemData = ajaxRequest.responseText;

alert( problemData[0] )

最佳答案

// 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);

关于PHP 将数组返回给 JavaScript Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com