我有一個返回一個數學問題一類的內部PHP函數:PHP返回數組一個JavaScript的Ajax調用
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])
看看JSON – Geert
你能鏈接到深入的教程嗎? – KiloJKilo