[英]How to add error handling in Jquery Ajax Form submission
This is my code 这是我的代码
<script type="text/javascript">
$(document).ready(function() {
$('#spc-comment-flag-form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data) {
if( data['error'] == false) {
var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!';
$('#spc-comment-flag-response').html(msg);
}
else {
$('#spc-comment-flag-response').html(data);
}
},
});
return false;
});
});
</script>
edit 编辑
on server side its something like this: 在服务器端它的东西是这样的:
@csrf_protect
@login_required
def flag(request, comment_id, next=None):
if not request.is_ajax():
raise Http404
data = {}
if request.method == 'POST':
...
data = simplejson.dumps(data)
return HttpResponse(data, mimetype="application/javascript")
else:
raise Http404
I am basically server side guy and seldom have to write JS. 我基本上是服务器端的人,很少写JS。 I sent "error" : true if there is an error with error message and "error" : false if no error on server!
我发送了“错误”:如果错误消息和“错误”错误,则为true:如果服务器上没有错误,则为false!
I don't know why in the above code the conditional logic is not working!! 我不知道为什么在上面的代码中条件逻辑不起作用!! Can anyone help me fix it?
任何人都可以帮我修复它吗?
try this one... 试试这个......
$(document).ready(function() {
$('#spc-comment-flag-form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data) {
if( data['error'] == false) {
var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!';
$('#spc-comment-flag-response').html(msg);
}
else {
$('#spc-comment-flag-response').html(data);
}
},
error: function (data) {
var r = jQuery.parseJSON(data.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
You may use this code.. if you want to handle the error in web request ... 您可以使用此代码..如果您想处理Web 请求中的错误...
http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/
$.ajax({
}).done(function (data) {
}).fail(function (jqXHR, textStatus) {
});
And about in your server side validation you could return the error using json ... 在您的服务器端验证中,您可以使用json返回错误...
you have to use 你必须使用
error: function( jqXHR jqXHR, String textStatus, String errorThrown){
...
...
}
success: function(data)
{
if(data.error){
//alert error
}
else{
//alert('Success');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Internal server error');
//some stuff on failure
}
This error
callback also handles the error, which are not caught at the server side. 此
error
回调还处理错误,这些错误未在服务器端捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.