2013-07-09 56 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']; 
相關問題