2010-06-17 130 views
2
to is not defined 
[Break on this error] setTimeout('updateChat(from, to)', 1); 

我得到這個錯誤...我使用Firebug進行測試,並在控制檯中出現。該錯誤對應於行chat.js 71和一個包裝此行的整體功能是:javascript錯誤:變量未定義

function updateChat(from, to) { 

    $.ajax({ 
     type: "POST", 
     url: "process.php", 
     data: { 
      'function': 'getFromDB', 
      'from': from, 
      'to': to 
     }, 
     dataType: "json", 
     cache: false, 
     success: function(data) { 

      if (data.text != null) { 
       for (var i = 0; i < data.text.length; i++) { 
        $('#chat-box').append($("<p>"+ data.text[i] +"</p>")); 
       } 
       document.getElementById('chat-box').scrollTop = document.getElementById('chat-box').scrollHeight; 
      } 
      instanse = false; 
      state = data.state; 
      setTimeout('updateChat(from, to)', 1); // gives error 
     }, 
    }); 
} 

該鏈接指向與函數調用getFromDB process.php和代碼是:

case ('getFromDB'): 

    // get the sender and receiver user IDs from their user names 
    $from = mysql_real_escape_string($_POST['from']); 
    $query = "SELECT `user_id` FROM `Users` WHERE `user_name` = '$from' LIMIT 1"; 
    $result = mysql_query($query) or die(mysql_error()); 
    $row = mysql_fetch_assoc($result); 
    $fromID = $row['user_id']; 

    $to = mysql_real_escape_string($_POST['to']); 
    $query = "SELECT `user_id` FROM `Users` WHERE `user_name` = '$to' LIMIT 1"; 
    $result = mysql_query($query) or die(mysql_error()); 
    $row = mysql_fetch_assoc($result); 
    $toID = $row['user_id']; 

    $query = "SELECT * FROM `Messages` WHERE `from_id` = '$fromID' AND `to_id` = '$toID' LIMIT 1"; 
    $result = mysql_query($query); 
    while($row = mysql_fetch_assoc($result)) { 

     $text[] = $line = $row['message']; 
     $log['text'] = $text; 

    } 

    break; 

所以我很困惑這條錯誤。 setTimeout('updateChat(from,to)',1);是不是參數updateChat進入函數相同的參數?或者他們是從別的地方被拉進來的,我必須定義其他地方和其他地方?任何想法如何解決這個錯誤?

感謝, 斯托伊奇

回答

7

這可能是因爲定義setTimeout功能時,這樣一來,當前函數的範圍不適用。我不知道說實話。應該很容易找出,雖然:嘗試

setTimeout(function() { updateChat(from, to) }, 1); 

如果它的工作,就是這樣。

如果不是這樣:您確定to首先被傳遞給您的第一個updateChat()電話嗎?

+0

+1擊敗我兩秒。 – MvanGeest 2010-06-17 18:41:47

+0

你是對的。 – SLaks 2010-06-17 18:42:58

+0

+1剛想說 – TheLQ 2010-06-17 18:43:07