为什么Ajax调用前的文本不显示

Why the text before Ajax call is not display?

本文关键字:文本 显示 Ajax 调用 为什么      更新时间:2023-09-26
function pdfToImgExec(file, IsfirstLogging, folder, round) {
  alert(file);
  var postString = file + '&' + IsfirstLogging + '&' + folder + '&' + round;
  var errorMsg = (folder == 'Incoming' ? '<p>error in incoming folder</p>' : '<p>error in other folder</p>');
  $.ajax({
    type: "POST",
    cache: false,
    async: false,
    url: "pdfToImgExec.php",
    data: {
      "data": postString
    },
    dataType: "html",
    beforeSend: function () {
      alert(file + 'a');
      $('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
    },
    success: function (data) {
      if(data == '1') {
        $('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
      } else if(round < 4) {
        $('#pdfToImgResult').html('<p>Fail to convert , retry ' + round + ' round <img src="loading.gif" height="20" width="20"/></p>');
        round++;
        pdfToImgExec(file, 'false', folder, round);
      } else {
        folder == 'Incoming' ? tempFailIncomingFiles.push(file) : tempFailResultFiles.push(file);
      }
    },
    error: function (x, t, m) {
      $('#pdfToImgResult').html(errorMsg);
      alert(t);
      releaseBtn();
    }
  });
}

这个ajax调用的问题是我可以在beforeend函数中警告(file + 'a'),但是

$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');

不工作,它将不显示任何内容,只跳转到

$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');

在ajax调用结束后。

async:false引起的吗?如何解决这个问题?谢谢。

这是因为您使用的是async: false,,所以功能阻塞,直到请求完成,防止重绘,直到一切都完成。

您似乎都设置了回调,因此似乎没有任何理由阻塞xhr请求。只要把async: false,取出来,你应该都准备好了。


下面是一个如何处理异步代码的快速示例。我删除了你的大部分代码,以保持简短。

 // --------------------------------new parameter-------------v
function pdfToImgExec(file, IsfirstLogging, folder, round, callback) {
  // your code...
  $.ajax({
    type: "POST",
    cache: false,
//  async: false,  // Remove this line! 
    url: "pdfToImgExec.php",
    data: {
      "data": postString
    },
    dataType: "html",
    beforeSend: function () {
      $('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
    },
    success: function (data) {
      // your code...
      // Invoke the callback, passing it the data if needed
      callback(data)
    },
    error: function (x, t, m) {
      // your code;
    }
  });
}

当您调用pdftoImgExec时,传递一个函数作为响应完成时将被调用的最后一个参数。这个函数就是你的代码恢复的地方。

pdfToImgExec(..., ..., ..., ..., function(data) {
    // resume your code here.
    alert(data);
})