2013-07-09 60 views
0

我有一个使用Google Closure编译器编译的Javascript文件,它给了我这个错误TypeError: f is undefined。当我查看编译的代码时,它不可能理解,但其中的一部分被注释掉了。我真的为难我得到这个错误,但我怀疑它与下面的脚本(这是我得到这个错误后编辑的唯一的事情)有关。来自Google Closure编译文件的TypeError

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

回答

1

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

这意味着当您致电发送时,您必须等待响应返回,您所做的是尝试读取下一行中的响应。您的引用也是一个问题,编译器会重命名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 
+0

我刚才读您的消息之前实现这一权利,但我非常欣赏你的解释。这个让我疯狂。有什么方法可以使请求同步吗?还是必须重新排列脚本? – niftygrifty

+0

@niftygrifty你必须重新安排,因为它不好使用同步请求(不知道goog.netXhrIo是否支持它)。你可以在'if(request.isSuccess())'块中做出响应。 – HMR

1

我认为这个问题是在这里:

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

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

var rawVocab = response['rawVocab']; 
var optionVocab = response['optionVocab']; 
相关问题