如何在从服务器获取数据之前显示加载功能?

How to show loading function before get data from server?

我使用 Ajax 和 SweetAlert2 库来使用警报 UI。我搜索了如何在从服务器获取数据期间显示加载过程,我想我可以使用 beforeSend 函数。我是这样写代码的

所以我把 Loading Process 代码放在了 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'
                    )
                }
            });
        }
    })
}

我从未使用过 SweetAlert,但我查看了他们的 website 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'
        })
      })
  }
}])

他们在他们的例子中使用 fetchpreConfirm,但在你的情况下,我想你可以尝试使用 return [=15] 的 preConfirm 属性=] 由 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
        }
    });
}

您只需将 showLoaderOnConfirm 设置为 true 即可在您单击继续按钮时显示预加载程序。然后,在 preConfirm 中添加 ajax 调用。只需确保 return 响应并捕获任何错误。

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>