Ajax表单提交和错误以JSON格式(django)显示在模板中



我有一个django网站:

.js

$("#contactForm").submit(function(event){
event.preventDefault(); //prevent default action 
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
$.getJSON( post_url , form_data,function( response ) {
//iterate json response
$.each( response, function(key, val) {
$("#msgSubmit").append( val + "<br />"); //append results to element
});
});
});

views.py

def contact_form(request):
form = ContactForm(request.POST or request.GET)
if form.is_valid():
data = {
'success': True,
}
status = 200
else:
data = {
'success': False,
'errors': form.errors.get_json_data(),
}
status = 400
return JsonResponse(data, status=status)

.html

<form id="contactForm" method="get" action="{% url 'contact-form' %}">
...
<button type="submit">Submit</button>
</form>
<div id="msgSubmit"></div>

当我提交表格时: 如果没有验证错误,我会在 #msgSubmit 出现"true"。 如果有错误,我什么也得不到。

我希望 JSON 错误出现在 #msgSubmit。

返回的 JSON 如下所示:

{"success": false, "errors": {"email": [{"message": "Please enter your email", "code": "required"}]}}

我试过了

alert(response);

但它不会发出警报。似乎在 ajax 请求期间没有返回 JSON。

此代码警报"失败"。

$.getJSON( post_url , form_data)
.done(function( response ) {
alert(response);
//iterate json response
$.each( response, function(key, val) {
$("#msgSubmit").append( val + "<br />"); //append results to element
});
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle your errors here
alert("fail");
});

所以看起来 $.getJSON(( 失败了。

以下:

$.getJSON( post_url , form_data)
.done(function( response, textStatus, jqXHR ) {
//iterate json response
$.each( response, function(key, val) {
$("#msgSubmit").append( val + "<br />"); //append results to element
}   );
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle your errors here
alert(jqXHR.responseText);
});

警报转储预期的 JSON 字符串:

{"success": false, "errors": {"name": [{"message": "Please enter your name", "code": "required"}], "subject": [{"message": "Please enter your subject", "code": "required"}], "email": [{"message": "Please enter your email", "code": "required"}], "budget": [{"message": "Please enter your budget", "code": "required"}], "message": [{"message": "Write your message", "code": "required"}]}}

当表单没有验证错误时,我可以通过将内容放在 .done 中来使用此逻辑,当存在验证错误时,将内容放入 失败。感谢您的帮助。

你可以使用jQuery的Ajax方法,如donefail等。更多细节在这里。

$.getJSON( post_url , form_data)
.done(function( response, textStatus, jqXHR ) {
//iterate json response
$.each( response, function(key, val) {
$("#msgSubmit").append( val + "<br />"); //append results to element
});
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle your errors here
});

最新更新