来自Google Closure编译文件的TypeError

时间:2013-07-09 14:47:33

标签: javascript json google-closure

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

2 个答案:

答案 0 :(得分:1)

我认为问题在于:

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

您没有正确引用您的媒体访问者。试试这个:

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

答案 1 :(得分: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