我在循环内调用了甜蜜警报功能,但是sweetalert仅向我显示一次,我认为当我执行简单警报时它会覆盖之前的sweetalert,bcz,它会弹出两次,但是甜蜜警报仅给我看一次我想做的是当我单击“确定”或“取消”按钮时显示甜蜜警报以显示第二或第三警报,否则不要根据循环迭代显示第二或下一警报这是我的代码
$(document).on('submit', 'form#tenant_login', function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method: "POST",
url: '{{ url('/tenant/login') }}',
data: data,
success: function(result){
if(result ) {
window.location = "{{ route('about') }}";
}
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
var testVar = error[0];
swal({
title: "Error!",
text: " " + error,
type: "error",
confirmButtonText: "OK"
});
});
}
}
});
});
答案 0 :(得分:0)
查看插件文档后,可以找到链接警报方法here。
我们可以看到一个例子,queue
方法将对象数组作为参数,因此您可以使用$.each
函数来构建该数组,然后将其传递给函数,如下所示(请注意,我设置了一个自定义错误数组,因为我没有您的确切代码,因此无法重现确切的数组,但是您可以重新排列它以适合您自己的代码):
var errors = ['error one', 'error two', 'error three']; //errors array from the response of AJAX request
var arrayOfErrorsToDisplay = []; //initialize the errors to display with the plugin
$.each(errors, function (i, error) {
arrayOfErrorsToDisplay.push({ title: 'Error!', text: error }); //add each error to the array
});
Swal.mixin({
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay) //we pass the array of errors to display to the queue
.then((result) => { //here you can set your own preferences for what to do when user clicks on OK, I just took the basic example for the plugin's documentation
if (result.value) {
Swal({
title: 'All errors have been shown!',
html:
'Your answers: <pre><code>' +
JSON.stringify(result.value) +
'</code></pre>',
confirmButtonText: 'Done!'
})
}
});
下面的工作片段:
var errors = ['error one', 'error two', 'error three'];
var arrayOfErrorsToDisplay = [];
$.each(errors, function (i, error) {
arrayOfErrorsToDisplay.push({ title: 'Error!', text: error });
});
Swal.mixin({
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay)
.then((result) => {
if (result.value) {
Swal({
title: 'All errors have been shown!',
html:
'Your answers: <pre><code>' +
JSON.stringify(result.value) +
'</code></pre>',
confirmButtonText: 'Done!'
})
}
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.all.min.js"></script>