2012-12-09 185 views
10

我試圖創建一個Javascript聊天,並在後端使用Python。這是我使用的代碼...ReferenceError:函數未定義 - JavaScript

<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>UDP Chat</title> 
    <!-- including JQuery just to simplify things --> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
    <script type="javascript/text"> 
    var chat_room_id = undefined; 
    var last_received = 0; 

    /** 
    * Initialize chat: 
    * - Set the room id 
    * - Generate the html elements (chat box, forms & inputs, etc) 
    * - Sync with server 
    * @param chat_room_id the id of the chatroom 
    * @param html_el_id the id of the html element where the chat html should be placed 
    * @return 
    */ 
    function init_chat(chat_id, html_el_id) { 
     chat_room_id = chat_id; 
     layout_and_bind(html_el_id); 
     sync_messages(); 
    } 

    /** 
    * Asks the server which was the last message sent to the room, and stores it's id. 
    * This is used so that when joining the user does not request the full list of 
    * messages, just the ones sent after he logged in. 
    * @return 
    */ 
    function sync_messages() { 
     $.ajax({ 
      type: 'POST', 
      data: {id:window.chat_room_id}, 
      url:'/chat/sync/', 
      dataType: 'json', 
      success: function (json) { 
       last_received = json.last_message_id; 
      } 
     }); 

     setTimeout("get_messages()", 2000); 
    } 

    /** 
    * Generate the Chat box's HTML and bind the ajax events 
    * @param target_div_id the id of the html element where the chat will be placed 
    */ 
    function layout_and_bind(html_el_id) { 
      // layout stuff 
      var html = '<div id="chat-messages-container">'+ 
      '<div id="chat-messages"> </div>'+ 
      '<div id="chat-last"> </div>'+ 
      '</div>'+ 
      '<form id="chat-form">'+ 
      '<input name="message" type="text" class="message" />'+ 
      '<input type="submit" value="Say"/>'+ 
      '</form>'; 

      $("#"+html_el_id).append(html); 

      // event stuff 
      $("#chat-form").submit(function() { 
       var $inputs = $(this).children('input'); 
       var values = {}; 

       $inputs.each(function(i,el) { 
        values[el.name] = $(el).val(); 
       }); 
       values['chat_room_id'] = window.chat_room_id; 

       $.ajax({ 
        data: values, 
        dataType: 'json', 
        type: 'post', 
        url: '/chat/send/' 
       }); 
       $('#chat-form .message').val(''); 
       return false; 
     }); 
    }; 

    /** 
    * Gets the list of messages from the server and appends the messages to the chatbox 
    */ 
    function get_messages() { 
     $.ajax({ 
      type: 'POST', 
      data: {id:window.chat_room_id, offset: window.last_received}, 
      url:'/chat/receive/', 
      dataType: 'json', 
      success: function (json) { 
       var scroll = false; 

       // first check if we are at the bottom of the div, if we are, we shall scroll once the content is added 
       var $containter = $("#chat-messages-container"); 
       if ($containter.scrollTop() == $containter.attr("scrollHeight") - $containter.height()) 
        scroll = true; 

       // add messages 
       $.each(json, function(i,m){ 
        if (m.type == 's') 
         $('#chat-messages').append('<div class="system">' + replace_emoticons(m.message) + '</div>'); 
        else if (m.type == 'm') 
         $('#chat-messages').append('<div class="message"><div class="author">'+m.author+'</div>'+replace_emoticons(m.message) + '</div>'); 
        else if (m.type == 'j') 
         $('#chat-messages').append('<div class="join">'+m.author+' has joined</div>'); 
        else if (m.type == 'l') 
         $('#chat-messages').append('<div class="leave">'+m.author+' has left</div>'); 

        last_received = m.id; 
       }) 

       // scroll to bottom 
       if (scroll) 
        $("#chat-messages-container").animate({ scrollTop: $("#chat-messages-container").attr("scrollHeight") }, 500); 
      } 
     }); 

     // wait for next 
     setTimeout("get_messages()", 2000); 
    } 

    /** 
    * Tells the chat app that we are joining 
    */ 
    function chat_join() { 
     $.ajax({ 
      async: false, 
      type: 'POST', 
      data: {chat_room_id:window.chat_room_id}, 
      url:'/chat/join/', 
     }); 
    } 

    /** 
    * Tells the chat app that we are leaving 
    */ 
    function chat_leave() { 
     $.ajax({ 
      async: false, 
      type: 'POST', 
      data: {chat_room_id:window.chat_room_id}, 
      url:'/chat/leave/', 
     }); 
    } 

    // attach join and leave events 
    $(window).load(function(){chat_join()}); 
    $(window).unload(function(){chat_leave()}); 

    // emoticons 
    var emoticons = { 
     '>:D' : 'emoticon_evilgrin.png', 
     ':D' : 'emoticon_grin.png', 
     '=D' : 'emoticon_happy.png', 
     ':\\)' : 'emoticon_smile.png', 
     ':O' : 'emoticon_surprised.png', 
     ':P' : 'emoticon_tongue.png', 
     ':\\(' : 'emoticon_unhappy.png', 
     ':3' : 'emoticon_waii.png', 
     ';\\)' : 'emoticon_wink.png', 
     '\\(ball\\)' : 'sport_soccer.png' 
    } 

    /** 
    * Regular expression maddness!!! 
    * Replace the above strings for their img counterpart 
    */ 
    function replace_emoticons(text) { 
     $.each(emoticons, function(char, img) { 
      re = new RegExp(char,'g'); 
      // replace the following at will 
      text = text.replace(re, '<img src="/media/img/silk/'+img+'" />'); 
     }); 
     return text; 
    } 
    </script> 
</head> 
<body> 
    <div id="chat"> 
    </div> 

    <script type="text/javascript"> 
    $(window).ready(function(){ 
     var chat_id = 1; 
     init_chat({{ chat_id }}, "chat"); 
    }) 
    </script> 
</body> 
</html> 

當我加載頁面在Firefox,我得到:

ReferenceError: init_chat is not defined  
init_chat({{ chat_id }}, "chat"); 

但是,函數init_chat明確定義。我究竟做錯了什麼? 我爲頁面創建了一個jsFiddle

+0

關於jsFiddle,你必須選擇jQuery,並使用「no wrap(head)」。那對我來說沒有錯誤。由於這兩件事情是與jsFiddle相關的,所以你的頁面上一定有其他事情發生。 – pimvdb

+0

@pimvdb你能看到正在創建的聊天框嗎? – cybertextron

+0

你也可以將MIME類型修改爲'type =「application/javascript」'或'「text/javascript」' – rjz

回答

13

當您在head部分中定義函數並在尚未初始化document時調用它們時會發生這種情況。移動script部分,在那裏進行初始化並試用。

由於您使用jQuery的,這也將是更好,如果你可以初始化的變量和函數下包圍整個腳本,並調用內部document的準備狀態的功能,它可能會工作。

$(document).ready(function(){ 
    var chat_id = 1; 
    init_chat({{ chat_id }}, "chat"); 
    // Something wrong here. Is it really chat_id inside {{ }}? 
}); 
+0

@Asad在答案中添加了問題。 :) –

+1

哎呦,猜我錯過了。我懷疑這個調​​用只是爲了'chat_id'。 –

2

在你的小提琴中,你定義了所有加載函數並在加載完成之前調用它們。以相反的方式做。這裏是一個固定的fiddle

您的對象文字語法也是重擊。 {{chat_id}}將導致語法錯誤。

0

只是改變type="javascript/text"type="text/javascript",你會發現它的工作。

+0

'

  • 11. 未捕獲ReferenceError:未定義test(函數)
  • 12. 未捕獲ReferenceError:函數未定義
  • 13. JavaScript未捕獲ReferenceError:未定義jQuery; Uncaught ReferenceError:$未定義
  • 14. ReactJS - 未捕獲ReferenceError:函數未定義
  • 15. ReactJS未捕獲ReferenceError函數未定義
  • 16. Uncaught ReferenceError:$未在jquery函數中定義
  • 17. ReferenceError:$未定義函數錯誤
  • 18. ReferenceError:使用onclick時未定義函數
  • 19. JavaScript - ReferenceError:未定義WebSocket
  • 20. ReferenceError:窗口未定義Javascript
  • 21. ReferenceError:____未定義
  • 22. JavaScript - 未捕獲ReferenceError:我的函數未定義
  • 23. ReferenceError:$未定義
  • 24. Google Script ReferenceError函數未定義
  • 25. ReferenceError:$未定義或未捕獲ReferenceError:$未定義
  • 26. Chrome:Uncaught ReferenceError:$未定義
  • 27. Javascript未捕獲ReferenceError:增量未定義
  • 28. ReferenceError:$未定義yii2
  • 29. Uncaught ReferenceError:$未定義
  • 30. JavaScript中的ReferenceError。在追加函數中未定義的字符