PHP 将数组返回给 JavaScript Ajax 调用

标签 php javascript ajax arrays

我在一个类中有 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/

相关文章:

javascript - 当 URL 少于/多于 X 个字符时隐藏内容

javascript - 修改 id 元素内 html 标签的样式

javascript - 使用对象将 javascript 变量传递给 php

php - phpunit 测试的执行顺序是什么?

javascript - 如何禁用 onkeyup 几秒钟

php - 检索自增数据库值

ajax - symfony2,从 Ajax 客户端调用服务

php - 如何从PHP中的URL获取多个同名参数并将所有记录插入表中

javascript - 返回当前位置 x 英里半径内的地点列表

javascript - MVC - 多参数 Ajax 调用