0

我在一个返回数学问题的类中有 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] )
4

4 回答 4

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);
于 2012-11-21T22:21:58.720 回答
1

尝试echo $problemData;而不是返回它。你打电话的时候有什么错误alert( problemData[0] )?ajax 只捕获字符串或 json 对象,因此唯一的方法是将此数组作为字符串返回并将其拆分为 js 或在 php 端的该数组上使用 json_encode

var data = problemData.split(' ');
alert(data[0]);
于 2012-11-21T22:14:28.087 回答
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;
于 2012-11-21T22:31:36.727 回答
0

您可以使用 json 对象从 javascript(AJAX) 向 php 发送和接收数据。使用 json_encode() 对 php 中的数据进行编码,然后以 html 或 text 的形式将其传递给 javascript。javascript 然后调用 json_decode 来检索数据并显示。

于 2012-11-22T09:56:04.147 回答