Ajax不起作用-提交时不会对数据和页面进行任何更改



试图在不渲染页面的情况下进行提交,但它不起作用,单击提交按钮时会渲染页面。如何更新以下字段的详细信息?

模板类似于这个

{% for i in userlist %}
<form method="POST" id="profileUpdate">
{% csrf_token %}
<input class="email" type="email" value="{{i.email}}" id="email">
<input class="dob" id="dob" type="text" value="{{i.date_of_birth}}" >
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
{% endfor %}

Ajax脚本

<script>
$(document).on('submit', '#profileUpdate', function (e) {
$.ajax({
type: 'POST',
url: '{% url "profileUpdate" %}',
data: {
email: $('#email').val(),
dob: $('#dob').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert("Success");
},
});
});
</script>

views.py

def profileUpdate(request):
response_data = {}
if request.get('action') == 'post':
email=request.POST.get('email')
dob=request.POST.get('dob')
response_data['dob'] = dob
ob=Employee.object.get(email=email)
ob.date_of_birth= dob
ob.save()
return HttpResponse('')

urls.py

urlpatterns = [    
path('registeredusers', registeredusers.as_view(), name="registeredusers"),
path('profileUpdate', views.profileUpdate, name='profileUpdate'),

]

使用preventDefault()来防止页面加载。

<script>
$(document).on('submit', '#profileUpdate', function (e) {
e.preventDefault(); //====> Add this line.
$.ajax({
type: 'POST',
url: '{% url "profileUpdate" %}',
data: {
email: $('#email').val(),
dob: $('#dob').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
alert("Success");
},
});
});
</script>

相关内容

最新更新