【发布时间】:2020-07-05 17:02:40
【问题描述】:
我一直在寻找这个解决方案,但没有一个解决方案有帮助。我正在通过 Django 学习 AJAX。然而,在下面的设置中,代码永远不会进入我的 Ajax 块,并且表单请求被直接传输,因此 request.is_ajax() 始终为 False。 .请帮帮我!!!
这是我的 create_post.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container pt-5">
<form method="POST" id="post-form">
{% csrf_token %}
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" id="description" placeholder="Description"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="row mb-2 posts">
{% for post in posts %}
<div class="col-md-6">
<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
<div class="col p-4 d-flex flex-column position-static">
<h3 class="mb-0">{{post.title}}</h3>
<p class="mb-auto">{{post.description}}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</body>
<script src="/static/jquery-2.2.4.min.js"></script>
<script src="/static/bootstrap.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: {'X-Requested-With': 'XMLHttpRequest'}
});
$(document).on('submit', '#post-form',function(e){
e.preventDefault();
var r = confirm("Are You sure we want to change status ?");
console.log("Its here atleast!!!");
$.ajax({
type:'POST',
url:'{% url "create" %}'
data:{
title:$('#title').val(),
description:$('#description').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success:function(json){
document.getElementById("post-form").reset();
$(".posts").prepend('<div class="col-md-6">'+
'<div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">' +
'<div class="col p-4 d-flex flex-column position-static">' +
'<h3 class="mb-0">' + json.title + '</h3>' +
'<p class="mb-auto">' + json.description + '</p>' +
'</div>' +
'</div>' +
'</div>'
)
},
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});
</script>
</html>
这是我的观点.py
def create_post(request):
# posts = Post.objects.all()
# response_data = {}
print("ENTERED create_posts")
print("is AJAX is "+str(request.is_ajax()))
posts = {}
posts['title'] = "Post1"
posts['description']= "Post 1 ka description"
# pdb.set_trace()
if request.POST.get('action') == 'post' and request.is_ajax():
title = request.POST.get('title')
description = request.POST.get('description')
response_data['title'] = title
response_data['description'] = description
# Post.objects.create(
# title = title,
# description = description,
# )
return JsonResponse(response_data)
return render(request, 'homeportal_app/create_post.html', {'posts':posts})
这是我的 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.create_post, name="create"),
]
【问题讨论】:
-
表单提交不是 AJAX 请求。
-
嗨,William,如何使用 Django 使表单提交 AJAX?