I'm trying to find out how to run JavaScript
in Django
to create chained forms. But at the first I want to find out how to even run JavaScript
. I've created a simple main.js
file which is in static
forder.
I've added a path to main.js
into the head of html
. And the script have to run when the page is loaded (just to be sure that I can step forward).
I've put alert
on the beginning of the function so I can see whether the js
has been run. But I can't see no alert
nor js
in chrome inspect
.
Could you guys tell me where is the problem?
main.js
$(document).ready(function(){
alert("OK")
$.ajax({
url: "get-possible-levels/",
type: "POST",
data: {language: $('#id_language').val()},
})
})
template:
{% extends 'base.html' %}
{% load static %}
{% block head %}
<script src="{% static "js/main.js" %}"></script>
{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ language_form }}
<button value="Update" type="submit">Submit</button>
</form>
{% endif %}
{% endblock %}
View:
@login_required
def create_order(request):
language_form = LanguageLevelForm(request.POST or None)
return render(request,'auth/jobs/create-job-test.html',context={'language_form':language_form})
EDIT: The main.js
seems to be executed but it does not alert
anything. I've checked inspect
(and I've tried to put semicolon after alert('ok')
) :
Your {% load static %}
should be {% load staticfiles %}
. After that try refreshing the page the way I described in my comment. BTW Are you actually including JQuery? Your question is about JavaScript. You should try to use a vanilla JavaScript alert before adding JQuery code just to troubleshoot it. If you can get that working try adding this to your <head>
<script src="jquery-1.12.0.min.js"></script>
Check if you have the path to the js file wrong.if your project folder has 2 folders inside (one with html files and 1 with Js files) then on your path with the ../ you go up one level on your folder and then go inside your javascript folder to find the file. So instead of
<script src="{% static "js/main.js" %}"></script>
write
<script src="../js/main.js"></script>
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.