0

我有一个用 Google Closure 编译器编译的 Javascript 文件,它给了我这个错误TypeError: f is undefined。当我查看编译后的代码时,无法理解,但其中的一部分已被注释掉。我真的很困惑为什么会收到此错误,但我怀疑它与以下脚本有关(这是我收到此错误后唯一编辑的内容)。

var response;

var request = new goog.net.XhrIo();

goog.events.listen(request, "complete", function(){

    if (request.isSuccess()) {

        response = request.getResponseText();

        console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());

    } else {

        console.log(
        "Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
        " - message: ", request.getLastError()
        );
    }

});


request.send("load_vocab.php");


var rawVocab = response[rawVocab];
var optionVocab = response[optionVocab];
alert(rawVocab.length);
alert(optionVocab.length);

这里还有 load_vocab.php ......

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

2 回答 2

1

你知道 xhr 请求是异步的吗?

这意味着当您调用 send 时,您必须等待响应返回,您所做的就是尝试读取下一行的响应。您的引用也是一个问题,编译器将重命名 rawVocab 和 optionVocab 但返回的数据不会重命名,因此您需要引用 ne8il 指出的这些值。

var response;
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
    if (request.isSuccess()) {
        window['console'].log("Now the response returned, setting response variable");
        response = request.getResponseText();
        console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
    } else {
        console.log(
        "Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(),
        " - message: ", request.getLastError()
        );
    }
});
window['console'].log("Sending request");
request.send("load_vocab.php");
window['console'].log("Trying to read response");
var rawVocab = response['rawVocab'];
var optionVocab = response['optionVocab'];

上述代码的输出将是:

Sending request
Trying to read response
Error
Now the response returned, setting response variable
于 2013-07-09T23:59:23.767 回答
1

我认为问题出在这里:

var rawVocab = response[rawVocab];
var optionVocab = response[optionVocab];

您没有正确引用您的属性访问器。尝试这个 :

var rawVocab = response['rawVocab'];
var optionVocab = response['optionVocab'];
于 2013-07-09T20:49:22.223 回答