来自Google Closure编译文件的TypeError

TypeError from Google Closure compiled file

本文关键字:TypeError 文件 编译 Google Closure 来自      更新时间:2023-09-26

我有一个用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);

您知道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

我认为问题出在这里:

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

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

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