【问题标题】:JQuery file download with Ajax使用 Ajax 下载 JQuery 文件
【发布时间】:2012-06-25 03:42:29
【问题描述】:

当我的用户选择生成报告时,我正在使用 John Culviner 出色的 fileDownload 插件来生成“请稍候”消息。

当用户点击一个链接时,我会向我的 PHP 发送一个 ajax 请求,它会在服务器上生成一个 PDF。那时我正在尝试更新 fileDownload 插件的成功处理程序中的链接。

我可能正在处理这个错误,但这是我的代码 - 非常感谢任何帮助。

$("body").on("click","##pdfLink", function(e){

    $.fileDownload($(this).attr('href'), {
        preparingMessageHtml: "Preparing your report, please wait...",
        failMessageHtml: "There was a problem generating your report, please try again."
    });

    // Build our data string.
    var strData = {method: "createPDF"};

    // Send a request to build our XL file.
    $.ajax({
        url: '/pdf.php',
        data: strData,
        type: 'get',
        dataType: 'json',
        success: function(data) {
            alert(data);
            $("##pdfLink").attr("href","/pdf/"+data);
        },
        error: function(e) {
            console.log(e);
        }
    });
    return false; 
    e.preventDefault(); 
})

此时,当我单击链接时,模式会正确显示“请稍候”消息。我的文件确实在服务器上构建(通过我的成功处理程序中的警报确认),并且我的 HREF 确实得到了更新。但是插件不会提示用户下载。

谢谢!

【问题讨论】:

  • 您能否添加“John Culviner 的出色文件下载插件”链接?

标签: jquery file download


【解决方案1】:

我正在使用以下代码在同一窗口中下载文件(不打开新标签)。它可以工作,虽然它没有任何错误支持...

function downloadURL(url, callback) {

    var id = 'hiddenDownloader';
    $('body').append('<iframe id="' + id + '" style="display: block" src="' + url + '"></iframe>');

    var $iframe = $('#' + id);
    $iframe.on('load', function () {
        $iframe.remove();
        // no error support
        callback();
    });
}


downloadURL('http://example.com', function() {
  alert('Done');
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    我也为我的应用程序使用 jquery.filedownload,我希望我的解决方案能帮助与我有类似要求的其他人;我稍微改变一下用法。即:

    1. 我将它与 rails3 一起使用

    2. 我想显示高音引导模式而不是 jquery 的对话框。

    A.客户端(前端),下图是HTML页面点击文件项时支持下载文件的功能:

    function DownloadFile(id, file_url, file_name, strTime){

    $.fileDownload(file_url, {
        successCallback: function (url) {
            $("#ilulModaldow").find('#file_name').html(file_name);
            $("#ilulModaldow").find('#file_created_at').html(strTime);
            $("#ilulModaldow").modal();
            //DATNT comment: $("#ilulModaldow") is a normal tweeter modal
        },
        failCallback: function (html, url) {
    
            alert('Connection error! Please try again');
        }
    });
    

    }

    B.服务器端(后端),我创建了一个发送文件的动作,这个动作是上面javascript函数的参数“file_url”:

    默认下载

    a=APostAttach.find(params[:id])
    send_file a.file.path(:original), :type => a.file_content_type
    #DATNT comment: below is the way I set cookies for jquery.filedownload plugin requirement
    cookies[:fileDownload] = true
    cookies[:Path] = "/"
    

    结束

    C.基于item(file)点击事件结合后端和字体端:

    $('#attach_<%= attach.id %>').click(function(){
        DownloadFile("<%= attach.id %>","<%= download_courses_path(:id => attach.id) %>","<%=attach.file_file_name %>","Uploaded at <%=  time_ago_in_words(attach.created_at).gsub('about','') + ' ago'%>");
    
    });
    

    【讨论】:

      【解决方案3】:

      可能,您需要开始下载,在收到链接参考后:

       $("body").on("click","##pdfLink", function(e){
          // Build our data string.
          var strData = {method: "createPDF"};        
      
          var self = this;
          var $pdfGeneratingDialog = $('<div>',{
                         title:"Generating PDF",
                         text: "Please wait..."
                         }).dialog({modal:true});
          // Send a request to build our XL file.
          $.ajax({
              url: '/pdf.php',
              data: strData,
              type: 'get',
              dataType: 'json',
              success: function(data) {
                 $pdfGeneratingDialog.dialog('close');
      
                 alert(data);
                 $(self).attr("href","/pdf/"+data);
                 //starting download process
                 $.fileDownload($(self).attr('href'), {
                     preparingMessageHtml: "Preparing your report, please wait...",
                     failMessageHtml: "There was a problem generating your report, please try again."
                 });             
              },
              error: function(e) {
                  console.log(e);
              }
          });
          return false;
      });
      

      【讨论】:

      • 这种方式违背了插件的目的,因为它应该在生成文件时给用户一些反馈。如果我在成功时弹出该消息,则该文件将已生成,用户将不会看到该消息,但一秒钟。
      • 除非没有收到您的链接引用,否则您的“下载者”怎么知道要下载什么??!!!!所以你需要等待,直到服务器响应。如果您想向用户提供反馈,请在 ajax 调用开始时显示您的“进度查看器”。
      • 工程师,不确定我是否关注,您介意发布一个示例,说明我在通话开始时如何显示消息吗?
      【解决方案4】:

      你不需要在 JS 中调用 ajax 函数。您的链接&lt;a href='yoursite.com/pdf.php' 使用此命令标识$(this).attr('href') pdf 服务器进程的位置。

      编辑:

      您的电话:

      // Build our data string.
      var strData = {method: "createPDF"};
      
      var $preparingFileModal = $("#preparing-file-modal");
      $preparingFileModal.dialog({ modal: true });
      
      $.fileDownload($(this).attr('href'), {
          httpMethod: "GET",
          data: strData
          successCallback: function (responseHtml, url) {
              $preparingFileModal.dialog('close');
              // In this case 
              $.fileDownload("/pdf/"+responseHtml, {
                  preparingMessageHtml: "Download file",
                  failMessageHtml: "Not work"
              });
      
          },
          failCallback: function (responseHtml, url) {
              $preparingFileModal.dialog('close');
              $("#error-modal").dialog({ modal: true });
          }
      });
      

      HTML:

      <div id="preparing-file-modal" title="Preparing report..." style="display: none;">
          We are preparing your report, please wait...
      
          <div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div>
      </div>
      
      <div id="error-modal" title="Error" style="display: none;">
          There was a problem generating your report, please try again.
      </div>
      

      【讨论】:

      • 我动态生成 pdf,传递参数,因此是 ajax 调用。
      • 在fileDownload calll中用这个命令data: strData传递参数
      • @JasonWells 我改为拨打两个电话。 &lt;a href="**URL** 之一生成第一个调用,第二个调用用于下载您的数据。
      • 很抱歉,回复晚了,我会试一试,但仍不能完全确定我是否遵循。如果它成功了,我会回来确保你得到支持 :) 感谢您的帮助!
      【解决方案5】:

      您是否尝试过调整超时时间?

      $.ajax({
              url: '/pdf.php',
              data: strData,
              type: 'get',
              dataType: 'json',
              timeout: 10000,
              success: function(data) {
                  alert(data);
                  $("##pdfLink").attr("href","/pdf/"+data);
              },
              error: function(e) {
                  console.log(e);
              }
          });
          return false; 
          e.preventDefault();
      

      【讨论】:

      • John:是的,我做到了,他的插件中有一个选项叫做 checkInterval,我也将它提高到 5000,但没有骰子。我的文件大约需要 2 秒才能生成。
      猜你喜欢
      • 1970-01-01
      • 2011-04-05
      • 2016-04-07
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      相关资源
      最近更新 更多