当Ajax失败时,我试图显示错误,但是我无法深入研究结果来显示确切的错误。
这是我在网络标签playground
{"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}
和JSON
message The given data was invalid.
errors {…}
title […]
0 The title field is required.
slug […]
0 The slug field is required.
Console
message
The given data was invalid.
errors
{…}
slug: Array [ "The slug field is required." ]
title: Array [ "The title field is required." ]
<prototype>: Object { … }
我能看到的是这样的:
message - The given data was invalid.
errors - [object Object]
error:function(data){
if( data.status === 422 ) {
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
console.log(key);
console.log(value);
errorsHtml += '<li><b>' + key + '</b> - ' + value + '</li>';
});
errorsHtml += '</ul></div>';
$( '#form-errors' ).html( errorsHtml );
} else if( data.status === 500 ){
var errors = data.responseJSON;
$( '#form-errors' ).append(errors.message);
} else {
var errors = data.responseJSON;
$( '#form-errors' ).append(errors.message);
}
}
我想从key
部分获得value
和errors
。
根据我上面的代码,如果我第二次value
循环,
//basic
$.each( errors , function( key, value ) {
//second time loop to get into errors
$.each( value , function( df, er ) {
console.log(df);
console.log(er);
});
errorsHtml += '<li><b>' + key + '</b> - ' + value + '</li>';
});
这不起作用。
如何将我的错误部分归还并退回key
和value
?
答案 0 :(得分:0)
您从errors
分配的data.responseJSON
变量包含您在操场上看到的值。
{"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}
您可以遍历此对象并直接访问该对象的errors
属性。请参阅下面我在哪里使用$.each(errors.errors, //...
来直接访问属性。以我的一些假设,您应该能够执行以下操作:
// mocking the data object for this example
var data = {responseJSON: {"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}};
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each(errors.errors , function( key, value ) {
errorsHtml += '<li><b>' + key + '</b> - ' + value[0] + '</li>';
});
errorsHtml += '</ul></div>';
$('#form-errors').html(errorsHtml);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-errors"></div>