使用 AJAX 显示 Laravel 验证错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49340608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
display Laravel validation errors with AJAX
提问by Eмαd
I have a Form
in Laravel
that submits with Ajax.every thing works well but the problem is that I can't render the validation's errors in HTML.
(I want to display the errors in <ul><li>
in my HTML)
我有一个Form
在Laravel
该提交带有Ajax.every东西效果很好,但问题是,我不能在HTML渲染验证的错误。
(我想<ul><li>
在我的 HTML 中显示错误)
Here is my Ajax request:
这是我的 Ajax 请求:
$(document).ready(function () {
$("#submit").click(function (xhr) {
xhr.preventDefault(),
$.ajax({
type: "POST",
contentType: "charset=utf-8",
dataType: 'json',
url: "{{route('messages.store')}}",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
data: {
name: $("#name").val(),
email: $("#email").val(),
phone: $("#company").val(),
subject: $("#subject").val(),
message: $("#message").val()
},
success: function () {
alert('True');
},
error: function (xhr) {
console.log((xhr.responseJSON.errors));
}
}, "json")
})
});
Console logs:
控制台日志:
Thanks for any help.
谢谢你的帮助。
回答by Sathishkumar Rakkiasamy
Try like this
像这样尝试
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
Here validation-errorsis the div id. You can use your own div id.
这里的validation-errors是div id。您可以使用自己的 div id。
回答by user9452884
<div id="error_email"></div>
Put this where you want your error to be displayed
把它放在你想要显示错误的地方
and then in your error function
然后在你的错误函数中
$('#error_email').html('<p>'+ xhr.responseJSON.errors.email[0] + '</p>')
回答by red1
You need to remove contentType: "charset=utf-8"
from Ajax
options to make it work correctly.
您需要contentType: "charset=utf-8"
从Ajax
选项中删除才能使其正常工作。
回答by user7747472
Validation return JSON response for an AJAX request not as what you have mentioned in your question. You can check in the lara docAnd the response you seeing in the console is a JSON array not HTML errors.
验证返回 AJAX 请求的 JSON 响应,而不是您在问题中提到的。您可以查看lara doc您在控制台中看到的响应是一个 JSON 数组,而不是 HTML 错误。
So what you can do is, you can catch any error in AJAX and check there itself if there is any error for email,message and so on. Based on that you can display error on the page.
因此,您可以做的是,您可以捕获 AJAX 中的任何错误,并自行检查电子邮件、消息等是否有任何错误。基于此,您可以在页面上显示错误。