ReferenceError:函数未定义 - JavaScript

时间:2012-12-09 20:05:36

标签: javascript html

我正在尝试在后端创建Javascript聊天,Python。这是我正在使用的代码...

<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

3 个答案:

答案 0 :(得分:15)

当您在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 {{ }}?
});

答案 1 :(得分:2)

在你的小提琴中,你在加载时定义所有函数并在加载完成之前调用它们。反过来说那样做。这是固定的fiddle

您的对象文字语法也很糟糕。 {{chat_id}}会导致语法错误。

答案 2 :(得分:-1)

只需将type="javascript/text"更改为type="text/javascript",您就会发现它有效。