Сладкое предупреждение переопределяет одно предупреждение в цикле - PullRequest
1 голос
/ 01 июня 2019

я вызываю функцию сладкого оповещения внутри цикла, но 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"
                         });



                    });
                }
            }
        });
    });

1 Ответ

0 голосов
/ 01 июня 2019

После проверки документации плагина можно найти метод оповещения о цепочке здесь .

Из примера видно, что метод 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) +
        '
», verifyButtonText: 'Готово!' }) } });

Рабочий фрагмент ниже:

	
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 &rarr;',
  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) +
        '
», verifyButtonText: 'Готово!' }) } });
<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>
...