Skip to main content
 首页 » 编程设计

jquery之使用 Ajax 和 jQuery 的 Django 表单!无法弄清楚如何在 URL 中将控制权从 Ajax 传递给 Python

2024年10月24日34qlqwjy

如何使用 python 文件 (project/controller/functions/email/sendemail.py) 处理使用 jQuery 从 ajax 发送电子邮件(或任何其他任务)?还是我做错了?

我不想像 Django tuts teach 那样重定向到另一个页面,我只想刷新表单并仅显示成功消息。 (我的消息和表单刷新工作正常,但无法处理 Ajax 中的 URL)。

我对此进行了高低搜索,但没有找到任何有用的东西。一些建议或示例链接将不胜感激。

我的文件与下面类似,除了我使用的是 jQuery Validate 所以有点不同但原理相同,我的表单在我的版本上使用 bootstrap 3 布局。

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> 

main.js

$('form#sendemail').on('submit', function() { 
  $.ajax({ 
    url: $(this).attr('action'), #(Targeting the action from the form. This is working as I can console.log the correct action as sendemail), 
    type: type, 
    data: data 
  }); 
}); 

我尝试重定向我的 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 中等效于返回值而不是 return。

在发送时,我在控制台中得到以下登录信息: 发布http://localhost:8888/sendemail 500(内部服务器错误)

请您参考如下方法:

您可以使用 HttpResponse 返回对 ajax 请求的响应。

import json 
from django.core.mail import send_mail 
from django.http import HttpResponse 
 
def sendemail(request): 
    data = {"message":"Failed"} 
    if (send_mail('Subject', 'Here is the message.', 'from@example.com', 
['to@example.com'], fail_silently=False)): 
        data = {"message":"Success"} 
    return HttpResponse(json.dumps(data), content_type="application/json") 

如果您使用的是 Django 1.7+,则使用 JsonResponse

from django.http import JsonResponse 
return JsonResponse(data) 

上面的代码会返回一个json响应,你会在ajax成功函数中得到这个

https://docs.djangoproject.com/en/1.9/ref/request-response/