我正在努力学习Ajax技术。所以,我创建了以下HTML部分:
<form id="form_{{ i }}_{{ j }}" action="" method="post">
{% csrf_token %}
<button class="ui green button" name="csrfmiddlewaretoken" value="{{ csrf_token }}" id="enroll_{{ i }}_{{ j }}" >Enroll</button>
</form>
$(function(){
$('button[id^="enroll"]').each(function(){
$(this).mouseup(function(){
$.ajax({
type: "POST",
url: "/",
data: {
'course': $(this).parents('div[id^="description_"]').find('a[id^="link_"]').text(),
'csrfmiddlewaretoken': $('button[name="csrfmiddlewaretoken"]').val()
},
success: courseFinder($(this)),
dataType: 'text',
error: function(req, err){ alert('my message' + err); }
});
});
});
});
function courseFinder(data, textStatus, jqXHR, it){
it.parents('form[id^="form_"]').attr()
}
});
def homepage(request):
if request.user.is_authenticated():
if request.method == "POST":
course = request.POST['course']
courses = Course.objects.get(course_title=course)
level = get_list_or_404(Level, level_hardiness="Beginner")
level_ids = [sets.id for sets in level]
courses = Course.objects.filter(course_level__in=level_ids)
send = {'level': level, 'courses': courses,}
return render(request, "Moolak/homepage.html", send)
else:
return render(request, "main/home_page.html", {'date': date.today()})
但它会在MultiValueDictKeyError
course = request.POST['course']
这是我的另一个问题:是否有必要使用输入? 欢迎任何帮助!感谢。