Forcing “Save As” dialog via jQuery GET

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 01:59:03

问题


I'm calling a jQuery "GET" on the test.php file code below.

I'm trying to get the script to pop a "Save As" dialog on the resulting test.ini file to allow it to be saved locally. However, although I can echo the result back to the jQuery fine, I can't seem to pop the "save as" dialog.

Update: Thanks to the solutions below, I just changed my $.get to a window.location.replace.

$('#test').click(
    function()
    {
        //$.get('<?php echo get_bloginfo('template_directory') ?>/test.php');
        window.location.replace("<?php echo get_bloginfo('template_directory') ?>/test.php");

    }
);

回答1:


You can't get an ajax request to show a "Save As" dialog, but what you CAN do is insert a hidden iframe element in the page, then set the source of that iframe to the url you want the user to download. Voila, there's your Save As.

Here's a copy and paste example:

$('a#linky').click(function(){
  var iframe = document.createElement("iframe"); 
  iframe.src = 'http://example.com/branding.zip'; 
  iframe.style.display = "none"; 
  document.body.appendChild(iframe);
  return false;
});



回答2:


You don't need an AJAX for this. Just navigate to the php in question and in that php use

header('Content-disposition: attachment;filename=whatever.dat');

This will pop-up the "save as" dialogue box and you'll remain on the original page.




回答3:


An AJAX request can't spawn the file download dialog. Consider instead opening your download target in a new window.



来源:https://stackoverflow.com/questions/6699461/forcing-save-as-dialog-via-jquery-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!