我正在尝试使用 Ajax 从数据库中提取 HTML 5 游戏的信息。正如您从下面的代码中看到的,我想在 PHP 中回显 JavaScript,以便它将存储在数据库中的变量推送到数组“rawVocab”和“optionVocab”中。但是当我检查这些数组的长度时,我发现它们是空的。
此外,console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
似乎没有调用此行。我的 eval() 实现可能有问题……不确定。
顺便说一句,我的代码使用了 Google Closure 库。
var rawVocab = new Array();
var optionVocab = new Array();
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
if (request.isSuccess()) {
response = request.getResponseText();
eval(response);
// print confirm to the console
console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
} else {
// print error info to the console
console.log(
"Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
" - message: ", request.getLastError()
);
}
});
request.send("load_vocab.php");
这是 load_vocab.php ......
$data = array();
try {
$conn = new PDO('mysql:host=localhost;dbname=tygrif_school', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT word, translation, example_sentence_1 FROM vocabulary_game WHERE game_type = :game_type');
$stmt->execute(array('game_type' => 'target'));
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['rawVocab'][] = $row;
}
$stmt = $conn->prepare('SELECT word, translation, example_sentence_1 FROM vocabulary_game');
$stmt->execute(array());
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$data['optionVocab'][] = $row;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($data);