繁体   English   中英

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

[英]Trying to open data retrieved from ajax to automatically download

现在,我有一个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文件的语法。

暂无
暂无

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

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