简体   繁体   中英

Django javascript not working $ is not defined

So, I've been working on a django project (using djagno 1.11) and I saw a really cool chat feature that someone mocked up (using django 2.0) here with their git repo here . I can recreate the entire project following the guide in its own app, but when I add it to my own I get into trouble. My current app uses bootstrap and has javascript to add items to cart and other such things and I wonder if that is getting in the way. That other javascript still works, the new javascript doesnt'. I get your basic error:

Uncaught ReferenceError: $ is not defined

and when I google search it I see that this means that something is being used before it is defined. I'm decent at python, but an extreme novice at javascript and so I'm not sure what is happening. Diving into the error, I see the following:

    <script src="https://project.s3.amazonaws.com/static/js/chat.js"></script>
<script>
    // For receiving
    sender_id = "";
    receiver_id = "1";

    //For sending
    $(function () {      <<--  This is where the error is pointing to.
        scrolltoend();
        $('#chat-box').on('submit', function (event) {
            event.preventDefault();
            var message = $('#id_message');
            send('', '', message.val());
            message.val('');
        })
    })
</script>

</div>

The above code is at the bottom of an html file that lives in the project/chat/templates/chat/chat.html and it references chat.js via {% static 'js/chat.js' %} which above is the aws line of code which lives in the cloudhere: project/static_my_proj/js/chat.js. This code i'm integrating has stuff like 'materialize.js' and 'materialize.min.js' which I trying to understand what they do.

I wonder if I'm trying to combine two types of javascript. I'm completely lost. Does anyone have any pointers? Is there any code I can provide that would help?

Thanks

You must add the following line

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

above / before

<script src="https://project.s3.amazonaws.com/static/js/chat.js"></script>

this line

I think you didn't declare the variables correctly.

Variables,

sender_id = "";
receiver_id = "1";

should be declared like this,

var sender_id = "";
var receiver_id = "1";

// if you are using ES6 then

const sender_id="";
const receiver_id = "1";

Other than this, maybe you should include jquery as Ahmet Zeybek said.

Materialize.js and Materialize.css is the part of the materialize framework which is similar to bootstrap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM