Как показать функцию загрузки до получения данных с сервера? - PullRequest
0 голосов
/ 12 февраля 2019

Я использую библиотеку Ajax и SweetAlert2, чтобы использовать интерфейс оповещения.Я ищу, как я могу показать процесс загрузки во время получения данных с сервера, и я подумал, что могу использовать функцию beforeSend.Я пишу такой код.

Поэтому я помещаю код процесса загрузки в beforeSend, но я не знаю, почему он не работает.Поэтому я хочу проверить, работает ли он в коде beforeSend, поэтому я пишу код console.log внутри него, и он действительно работает.Но я не знаю, почему Swal.showLoading ();код не работает.

Когда я просто набираю его в консоли Google, он работает.

Загрузка кода проста.

Swal.showLoading();

И я хочу, когда он закончит показывать код завершения.

/* Mypage */
function getData() {
    Swal.fire({
        title: 'Do you want to get data from Github?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        allowOutsideClick: false,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Get DATA!'
    }).then((result) => {
        if (result.value) {
            $.ajax({
                type: "POST",
                // contentType: "application/json",
                url: `/${userId}/admin/getData`,
                dataType: "json",
                beforeSend: function () {
                    Swal.showLoading();
                    console.log('Loading');
                },
                success: function (redrawData) {
                    console.log(JSON.stringify(redrawData));
                    let existTable = $('#dataTable').DataTable();
                    existTable.destroy();
                    $('#dataTable').DataTable({
                        aaData: redrawData, // Returned Data from Server
                        aoColumns: [{
                                mData: 'id',
                                "render": function (value, type, row) {
                                    return `<a href="/${userId}/${row.id}">${row.id}</a>`;
                                }
                            },
                            {
                                mData: 'name'
                            },
                            {
                                mData: 'type'
                            },
                            {
                                mData: 'url'
                            },
                            {
                                mData: 'imgurl',
                                "render": function (value, type, row) {
                                    return `<img src="${row.imgurl}">`;
                                }
                            },
                            {
                                mData: 'sumlang'
                            },
                            {
                                mData: 'pjdate1'
                            },
                            {
                                mData: 'pjdate2'
                            },
                            {
                                mData: 'githuburl'
                            }
                        ]
                    })
                },
                complete: function () {
                    Swal.fire(
                        'Get!',
                        'Your file has been deleted.',
                        'success'
                    )
                },
                error: function (e) {
                    Swal.fire(
                        'Failed to save',
                        'If this message is output continuously, please contact to administrator.',
                        'error'
                    )
                }
            });
        }
    })
}

Ответы [ 2 ]

0 голосов
/ 12 февраля 2019

Вы можете просто установить showLoaderOnConfirm в значение true, чтобы отображать предварительный загрузчик при нажатии кнопки продолжения.Затем добавьте вызов ajax внутри preConfirm.Просто обязательно верните ответ и поймайте все ошибки.

Swal.fire({
  title: 'Submit your Github username',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Look up',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`//api.github.com/users/${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
      title: `${result.value.login}'s avatar`,
      imageUrl: result.value.avatar_url
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
0 голосов
/ 12 февраля 2019

Я никогда не использовал SweetAlert, но я посмотрел на их сайте exmaple и нашел это

const ipAPI = 'https://api.ipify.org?format=json'

Swal.queue([{
  title: 'Your public IP',
  confirmButtonText: 'Show my public IP',
  text:
    'Your public IP will be received ' +
    'via AJAX request',
  showLoaderOnConfirm: true,
  preConfirm: () => {
    return fetch(ipAPI)
      .then(response => response.json())
      .then(data => Swal.insertQueueStep(data.ip))
      .catch(() => {
        Swal.insertQueueStep({
          type: 'error',
          title: 'Unable to get your public IP'
        })
      })
  }
}])

Они используют fetch с preConfirm в своем примере, но вв вашем случае, я думаю, вы можете попытаться использовать атрибут preConfirm, который возвращает Promise, созданный JQuery $.ajax() функция

Пример:

/* Mypage */
function getData() {
    Swal.fire({
        title: 'Do you want to get data from Github?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        allowOutsideClick: false,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Get DATA!',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: function(){
            return $.ajax(...); //Your ajax function here
        }
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...