0

在 js(jquery 1.7)中,我使用以下代码:单击按钮时应该发生两个操作:1. 显示状态(显示 html) 2. 运行函数以生成 pdf

$( "#create_box" ).on("click", "#make_pdf_btn",function(){
$('.pdf_status0').html('Generating report...' );  // problematic line
 make_pdf2();
 return false;
  });

然后:

function make_pdf2(){
    $.ajax({
            type: "GET",
            url: "make_pdf.php",   // pdf is created and saved
            async: false,          // synchronous  ajax
            success: function(html){ strReturn = html; }
    });

   if ( strReturn == 'pdfok' ){ 
        $('.pdf_status0').html('Done!<br>');
        $('.pdf_status').show();
       } else {
         $('.pdf_status').html('Error creating pdf.' );  
       }
  return false;      

}

问题是那行 $('.pdf_status0').html('Generating report...' ); 在 Firefox 中运行正常,文本“生成报告...”显示在 div 中,然后替换为“完成!”。但是 Chrome 和 IE8 不显示“正在生成报告..”只有“完成!” 并创建了pdf。

如果我使用 alert('text') 而不是 jquery html,它会运行并在 IE、chrome 和 firefox 中显示警报

4

2 回答 2

1

我认为应该是这样的:

$(function(){
   $( "#create_box" ).on("click", "#make_pdf_btn",function(){
     $('.pdf_status0').html('Generating report...').promise().done(function(){
        make_pdf2();
     });
     return false;
   });
});

function make_pdf2(){
    $.ajax({
        type: "GET",
        url: "make_pdf.php",   // pdf is created and saved
        async: false,          // synchronous  ajax
        success: function(html){ 
             strReturn = html;
             if ( strReturn == 'pdfok' ){ 
                  $('.pdf_status0').html('Done!<br>');
                  $('.pdf_status').show();
             } else {
                  $('.pdf_status').html('Error creating pdf.' );  
             } 
        }
   });      
}
于 2013-02-03T05:35:04.727 回答
0

当您进行同步 ajax 调用时,它通常会锁定浏览器,直到响应被处理,这意味着屏幕不会重新绘制以显示您的“正在生成报告...”消息,直到为时已晚,因为您已经更改了它到“完成!”。

几乎没有使用同步 ajax 的充分理由,而且我在您的代码中看不到任何无法轻松重构为异步的内容 - 这使浏览器有机会在 ajax 调用正在进行时重新绘制:

function make_pdf2(){
    $.ajax({
            type: "GET",
            url: "make_pdf.php",   // pdf is created and saved
            async: true,          // use Asynchronous  ajax
            success: function(html){
               // do all required processing on response in the success callback
               strReturn = html;
               if ( strReturn == 'pdfok' ){ 
                  $('.pdf_status0').html('Done!<br>');
                  $('.pdf_status').show();
               } else {
                  $('.pdf_status').html('Error creating pdf.' );  
              }
           }
    });

  return false;      
}

话虽如此,我偶尔会发现较旧的 IE(不确定 IE8)仍然会以一种可以通过setTimeout()hack 修复的方式感到困惑:

setTimeout(make_pdf2, 4); // make call to make_pdf2() async too
于 2013-02-03T05:17:47.907 回答