如何使用python文件(project/controller/functions/email/发送电子邮件.py)使用jQuery处理从ajax发送电子邮件(或任何其他任务)?还是我做错了?在
我不想重定向到另一个页面,比如Django tuts teach,我只想刷新表单并显示成功消息。(我的消息和表单刷新工作正常,但在Ajax中对URL的处理不好)。在
我在这上面搜了很多遍,但是没有找到有用的东西。一些建议或例子链接将不胜感激。在
我的文件与下面类似,只是我使用jqueryvalidate,所以有点不同,但是主体相同,我的表单是在我的版本上使用bootstrap3来布局的。在
index.html
<form method="post" action="sendemail" id="sendemail">
<input name="name" type="text" />
<input name="email" type="email" />
<input name="submit" type="submit" value="send" />
</form>
^{pr2}$main.js
我尝试将我的URL重定向到目标文件,这样我就可以使用Ajax中的URL来定位文件,如下所示。在
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from . import views
from .controller.functions.email import sendemail
urlpatterns = [
url(r'^$', views.Home, name='home'),
url(r'^sendemail', sendemail, name='sendemail'),
url(r'^admin/', include(admin.site.urls)),
]
我的控制台有一个500服务器错误。在
sendemail.py
from django.core.mail import send_mail
def sendemail(request):
if (send_mail('Subject', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)):
print(1) #Success
else:
print(99) #Fail
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect
from .forms import ContactForm
@csrf_protect
def Home(request):
tpl = 'main/index.html'
contactNotify = ""
contactForm = request.POST
if request.method == 'POST':
contactForm = ContactForm(request.POST)
if ContactForm.is_valid():
return render(request, tpl, context)
else:
contactForm = ContactForm()
context = {
'contactForm' : contactForm
}
return render(request, tpl, context)
在php中,我使用echo返回jQuery,因此我假设print在Python中等价于返回值而不是返回。在
发送时,我在控制台中获得以下登录: POSThttp://localhost:8888/sendemail500(内部服务器错误)
您可以使用HttpResponse返回对ajax请求的响应。在
如果您使用的是django1.7+,那么使用JsonResponse
^{pr2}$上面的代码将返回一个json响应,您将在ajax中获得这个成功函数
https://docs.djangoproject.com/en/1.9/ref/request-response/
Django的工作方式不同
在网址.py在
^{pr2}$在视图.py在
记住
我不知道你为什么要在你的家庭视图里听POST请求。。但我认为还有更多的事情要解决,但请尝试我的建议
相关问题 更多 >
编程相关推荐