[英]How to fire a Javascript alert and then redirect the page after user clicks 'ok' in Django?
I have contact form on my Django website. 我在Django网站上有联系表。 When someone clicks submit, I would like to use a Javascript alert to inform them that their message has been sent and then redirect them to back to the homepage.
当某人单击“提交”时,我想使用Javascript警报来通知他们其消息已发送,然后将其重定向回首页。 I've setup the HttpResponseRedirect part in my view, but I'm struggling to get the JS piece working alongside.
我已经在我的视图中设置了HttpResponseRedirect部分,但是我正在努力使JS部分协同工作。 Here is my views.py:
这是我的views.py:
from datetime import date
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from .form import ContactUsForm
def contact(request):
form = ContactUsForm(request.POST or None)
if form.is_valid():
this_form = form.save(commit=False)
this_form.save()
return HttpResponseRedirect('/')
return render_to_response('contact/form.html', locals(), context_instance=RequestContext(request))
In your template, you could use something as simple as this (uses some jQuery): 在模板中,您可以使用以下简单的内容(使用一些jQuery):
$(function()
{
$('form').on('submit', function(){
alert('Your message has been sent!');
});
});
Note a few things: 请注意以下几点:
This is a little misleading, as it alerts the user that their message has been sent, even if it doesn't actually get sent (it never checks with the server to make sure). 这有点误导,因为它警告用户他们的消息已经发送,即使实际上没有发送(它也不会与服务器进行确认)。 So, if there was some error in the form, this would definitely mislead the user.
因此,如果表单中存在某些错误,则肯定会误导用户。
This alert will bind to any form on the page, so it may be better to target the specific form with its id. 该警报将绑定到页面上的任何表单,因此最好将特定表单及其ID作为目标。
So that's the quick-and-dirty solution. 这就是快速而又肮脏的解决方案。 I'd recommend, though, using Django's messages framework instead.
不过,我建议改用Django的消息框架 。 Basically, you'd not use any Javascript to submit the form, but instead add something like this to your view:
基本上,您不会使用任何Javascript来提交表单,而是在您的视图中添加如下内容:
from django.contrib import messages
messages.success(request, 'Message sent.')
And then in your template (best to add this to your base template so it shows up wherever the user goes, since messages expire with every page-load: 然后在您的模板中(最好将其添加到基本模板中,这样它就可以显示在用户到处的位置,因为每次页面加载时邮件都会过期:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.