尝试打开从ajax检索到的数据以自动下载

Trying to open data retrieved from ajax to automatically download

本文关键字:数据 下载 检索 ajax      更新时间:2023-09-26

现在,我有一个web应用程序,它使用jquery ajax对我的后端进行调用(参数通过表单从一个调用更改为另一个调用),并检索一个xml文件。我想将xml数据放入一个具有不同扩展名的文件中,用于私人应用程序。

基本上,我只希望用户能够点击一个按钮,它会自动提示他们"打开或保存"一个包含返回的ajax xml数据的文件。

我曾尝试过使用php发送原始http头,但我不知道如何使其工作。我正在用javascript和jquery编写所有这些。

下面的代码所做的唯一一件事是(1)进行Ajax调用,(2)将XML写入HTML页面,(3)打开HTML页面。

var format = function() {   
  $("button#format").click(function() {
    $("#form").submit();
    $.ajax({
      url: "find",
      beforeSend: function (xml) {
        xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
      },
      data: $("form#form").serialize(),
      dataType: "html",
      success: function(xml) {
        xmlWindow = window.open("download.ivml");
        xmlWindow.document.write(xml);
        xmlWindow.focus();
      },
      error: function(request) {
        $("#webdiv").html(request.responseText);
      }
    });
  });
};

没有必要在AJAX范式中强制使用这样的东西,除非您需要在将检索到的数据提供给用户之前对其进行处理,否则这应该能够在php中完成。所以我会这样做:

<form id="format" action="download.ivml" target="_blank">
...
</form>

在jquery中,像这个一样修改action

​$('#format')​.submit(function(){
    // tweaking the post data, otherwise this whole block is not needed.
    return true;    
})​;

最后,在我的服务器上使用.htaccess文件来处理那个奇怪的URL download.ivml

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$  /path/to/where/I/process/the/request

但不太确定最后一个.htaccess文件的语法。