使用 AJAX 显示 Laravel 验证错误 [英] display Laravel validation errors with AJAX
本文介绍了使用 AJAX 显示 Laravel 验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Laravel
中有一个 Form
用 Ajax 提交.一切正常,但问题是我无法在 HTML 中呈现验证错误.
(我想在我的 HTML 中显示
中的错误)
这是我的 Ajax 请求:
$(document).ready(function () {$("#submit").click(function (xhr) {xhr.preventDefault(),$.ajax({类型:POST",contentType: "charset=utf-8",数据类型:'json',url: "{{route('messages.store')}}",标题:{"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")},数据: {名称:$("#name").val(),电子邮件:$("#email").val(),电话:$("#company").val(),主题:$("#subject").val(),消息:$("#message").val()},成功:函数(){警报('真');},错误:函数(xhr){console.log((xhr.responseJSON.errors));}}, "json")})});
<块引用>
控制台日志:
感谢您的帮助.
解决方案
试试这个
错误:函数(xhr){$('#validation-errors').html('');$.each(xhr.responseJSON.errors, function(key,value) {$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');});},
这里 validation-errors 是 div id.您可以使用自己的 div id.
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)
Here is my Ajax request:
$(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.
解决方案
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-errors is the div id. You can use your own div id.
这篇关于使用 AJAX 显示 Laravel 验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文