简体   繁体   中英

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. The ajax call looks like this:

                            $.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:

<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. When the code in iframe runs the file will download. So, I need help with parsing this html to page and then running this code block.

Thanks in advance.

Alright, so first you wanna grab that src from the iframe, then create anchor dom element and just click that. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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