【发布时间】:2020-10-16 18:45:23
【问题描述】:
我有一个表单,我想用它向我的后端视图发送数据。
<form class="modal-content animate" method="POST" id="make_admin">
{% csrf_token %}
<!-- List users to make admin -->
<div class="container">
<label for="uname"><b>User: </b></label>
<select id="select_user">
{% for employee in users %}
{% if not employee.is_admin %}
<option value="{{ employee.id }}">{{ employee.first_name }} {{ employee.last_name }}</option>
{% endif %}
{% endfor %}
</select>
<button type="submit">Make Admin</button>
</div>
</form>
Javascript:
$(document).on('submit', '#make_admin' ,function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'{% url 'cerberus_mvp:make_admin' %}',
data:{
id: $('#select_user').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success:function(response){
$(".update").html(response)
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});
我的问题是当点击提交按钮时没有任何反应,页面似乎只是刷新。似乎从未到达过javascript代码。任何想法为什么?提前致谢。
编辑:如果我将 window.alert("hello"); 添加到 javascript 代码中,则不会得到它。认为错误在于 html 或 $(document).on('submit', '#make_admin' ,function(e){ 行。
【问题讨论】:
-
在您尝试附加事件时是否存在表单?换句话说 document.getElementById('make_admin')
-
你测试的是什么浏览器?在提交处理程序末尾添加
return false;有帮助吗? -
你有一个类
update的元素吗?您没有在控制台中收到错误消息? -
回答问题:浏览器是chrome,有一个元素“update”,它是一个空的div来显示“Success”之类的东西,没有错误信息。
-
您的浏览器控制台是否显示任何错误?
标签: javascript python django ajax forms