【发布时间】:2019-04-12 02:44:46
【问题描述】:
我正在尝试在 Django 中创建一个简单的 Web 应用程序并尝试使用 Ajax,因此页面不会刷新。这个应用程序的唯一目标是让表单接受一些用户输入,并且在提交表单时不会刷新。但是,由于某种原因,当我单击按钮时不会发生这种情况。这是索引页面:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form">
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="email"> email:<br></label>
<input type="text" id="email"/>
</div>
<div>
<label for="password" > password:<br></label>
<input type="text" id="password"/>
</div>
<div>
<input type="submit" value="submitme"/>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submitme', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
email:$('#email').val(),
password:$('#password').val(),
}
success.function(){
alert('created')
}
})
}
</script>
</html>
这是我的主要 urls.py 文件:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
import testapp
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', testapp.views.index),
url(r'^user/create/$', csrf_exempt(testapp.views.create_user))
]
我的views.py文件:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
def create_user(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
User.objects.create(
name = name,
email = email,
password = password
)
return HttpResponse('')
最后是 models.py 文件:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
email = models.EmailField()
password = models.CharField(max_length = 128)
这样做的目的是当单击按钮时,它应该向后端发送一个 POST 请求,该请求创建一个 User 类型的对象并将其保存到数据库中。但是,由于某种原因,当我单击提交时,根据 Chrome 上的网络工具,没有发送任何 POST 请求。有人可以帮我吗?
【问题讨论】:
-
$(document).on('submitme', '#new_user_form', function(e)){- 这看起来不对,第一个参数肯定应该是'click'? -
您好尝试过这个:$('#submit').click(function()) 而不是以前的标头,但它没有任何区别,也没有发送 POST 请求
-
只有在您提供提交按钮
id="submit"时才有效 -
是的,但仍然没有发送帖子请求。
标签: python jquery django post web-applications