简体   繁体   English

使用从ajax调用返回的html下载文件

[英]Download file using html returned from ajax call

I'm trying to download a file on the same page using html returned from the ajax call.我正在尝试使用从 ajax 调用返回的 html 在同一页面上下载文件。 The ajax call looks like this: ajax 调用如下所示:

                            $.ajax({
                                url: './xyz.cshtml',
                                type: "POST",                               
                                data: {
                                    //some validation and data to send to server.
                                },
                                success: function (data, status, xhr) {
                                    //alert('status: ' + status + ', data: ' + data);
                                    var result = $(data);
                                    
                                    console.log(result);
                                    result.appendTo("body");
                                }
                             });

The html looks like this: html 看起来像这样:

<iframe width='1' height='1' frameborder='0' src='http://server//some_folder/some.xlsm'></iframe> <script>document.body.style.cursor = 'default';</script>

Basically, I want to parse this iframe and then run it on the same page.基本上,我想解析这个 iframe,然后在同一页面上运行它。 When the code in iframe runs the file will download.当 iframe 中的代码运行时,文件将下载。 So, I need help with parsing this html to page and then running this code block.因此,我需要帮助将此 html 解析为页面,然后运行此代码块。

Thanks in advance.提前致谢。

Alright, so first you wanna grab that src from the iframe, then create anchor dom element and just click that.好的,所以首先您想从 iframe 中获取该 src,然后创建锚点 dom 元素并单击它。 I guess that should do the trick我想这应该可以解决问题

var ajaxResponse = "<iframe width='1' height='1' frameborder='0' src='http://server//some_folder/some.xlsm'></iframe> <script>document.body.style.cursor = 'default';</script>";

// this function will simply download the file
function download(filename, dataurl) {
  var a = document.createElement("a");
  a.href = dataurl;
  a.setAttribute("download", filename);
  a.click();
}

var regex = /<iframe.*?src='(.*?)'/;
var src = regex.exec(ajaxResponse)[1]; // src from that iframe

download("SomeFileName.xmlsm", src);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM