[英]Onclick button does not call js function in django
I have a button that must call my js function, but nothing happens when i do (there is no get requests)我有一个必须调用我的 js function 的按钮,但是当我这样做时没有任何反应(没有获取请求)
My HTML:我的HTML:
<button type="button" id="checker" id="button{{answer.id}}" onclick="mark_as_correct({{answer.id}});">
</button>
My JS function:我的 JS function:
function mark_as_correct(qid) {
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: 'url answerajaxcorrect',
type: 'post',
data: {id: qid},
success: function(data) {
document.getElementById('correct' + qid).innerHTML = "Correct!"
var button = document.getElementById('button' + qid)
button.parentNode.removeChild(button)
},
failure: function(data) {
alert('error')
}
})
}
I do include my js to template:我确实将我的 js 包含到模板中:
{% load static %}
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
And there is how my view looks like:我的观点是这样的:
@login_required
def correct_ajax(request):
qid = int(request.POST.get("id"))
answer = get_object_or_404(Answer, id=qid)
if answer.author == request.user:
answer.is_correct = True
answer.save()
return JsonResponse({
"is_correct": True,
})
else:
return JsonResponse({
"is_correct": False,
})
I am new to js and django, so it is hard for me to understand the source of my problem, please help.我是 js 和 django 的新手,所以我很难理解问题的根源,请帮忙。
onclick="mark_as_correct({{answer.id}});"
The function reference you pass to onclick
needs to be able to take an event
parameter.您传递给
onclick
的 function引用需要能够采用event
参数。 When you point to a function with assigned argument to onclick
, the browser will execute the function at read time, and assign the result of that function to onclick
.当您指向 function 并将参数分配给
onclick
时,浏览器将在读取时执行 function,并将该 function 的结果分配给onclick
。
In your case, you can just create an anonymous function to do the trick:在你的情况下,你可以创建一个匿名的 function 来完成这个技巧:
<button type="button" id="checker" id="button{{answer.id}}" onclick="function() { mark_as_correct({{answer.id}}) };">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.