保存ajax响应文件

时间:2015-06-11 09:18:50

标签: javascript ajax extjs

我们假设我有以下按钮代码:

Ext.create('widget.button', {
    handler: function () {
        Ext.Ajax.request({
            method: 'POST',
            url: 'index.php?r=store/exportXLS',
            params: {
                queryName: me.exporting.name,
                queryGroups: Ext.JSON.encode(me.exporting.groups)
            },
            success: function (response) {
                //???
            }
        });
    },
    dock: 'top',
    text: 'Экспорт в XLS'
});

因为groups变量包含太多参数,我必须通过POST发送所有数据。操作“store / exportXLS”返回我想要保存为XLS的有效html。我无法使用window.open(),因为每次都会阻止这些窗口。所以,问题:是否可以将response.responseText保存为文件? (在我的情况下是Excel)

更新: 根据您的要求,我发布了html。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns:o="urn:schemas-microsoft-com:office:office"

xmlns:x="urn:schemas-microsoft-com:office:excel"

xmlns="http://www.w3.org/TR/REC-html40">
<head>
    <meta http-equiv="Content-Type" content="application/excel; charset=utf-8"/>
    <title>hideshow</title>
</head>
    <body>
                <table border="1">
            <thead>
                <tr style="font-weight: bold">
                    <td>Пациент</td><td>Лекарственное средство</td>
                </tr>
            </thead>
            <tbody>
                <tr><td>Ажыфорафо А.В. <br />№ истории болезни: Х-34<br /></td><td>Аминокапроновая к-та р-р д/инф.5% фл.100мл Белмедпрепараты РУП,Республика Беларусь<br />Срок годности: 2016-01-01<br />Стоимость: 52.4700000<br />ЛС ОТМЕНЕНО<br /></td></tr>
            </tbody>
        </table>
    </body>
</html>

使用PHP我按如下方式设置标题:

header("Content-Type: application/excel; charset=UTF-8");
header("Content-Disposition: attachment; filename=journal.xls");

2 个答案:

答案 0 :(得分:0)

长话短说:不,你不能跨浏览器将js中的随机数据保存到文件中。您可以检查FileSaver.js以获得部分解决方案,但这个问题应该在服务器端解决(服务器应该生成一个您可以参考的短链接)。

答案 1 :(得分:0)

您的HTML对Excel无效。您应该需要表标记。为此,您可以使用split:

功能
 var str = response.split('<table border="1">');
 strTmp = str[1].split('</table>');
 var html = '<table border="1">' + strTmp[0] + '</table>';

当您的html有效时,您可以使用以下代码:

JS

var url='data:application/vnd.ms-excel,' + escape(html) ; 
var link = document.getElementById("downloadLink");
link.setAttribute("href", url);
link.setAttribute("download", "export.xls");
link.click();

HTML

<a id="downloadLink" href="" style="display: none;">