首页 > 解决方案 > 从 Ajax 请求 (Struts 2 / jQuery) 下载 Excel 文件:“parsererror”、“Invalid XML”或“位置处的 JSON 中的意外标记...”

问题描述

我需要通过 Ajax 请求触发 Excel 文件的下载。(这必须是 Ajax,因为这些行是从显示的客户端 DataTable、过滤等动态生成的——所以我抓住了显示的 GUI 行)。

我在客户端/服务器端跟踪代码,一切正常,生成工作簿,但由于错误,下载永远不会在最后触发。

$.ajax({
    url: "exportSearchResults",
    dataType: "json", /* I comment out this line or leave it in */
    type: "post",
    data: {
        'exportSearchResultsJson': JSON.stringify(result)
    },
    success: function( data ) {
        alert('Success');
        console.log(data);
    },
    error: function(xhr, error, thrown) {
        alert('Error');
        console.log(xhr + " " + error);
    }
});

错误:解析器错误(显示在 Chrome 中)

1) 当 dataType = JSON 时:

SyntaxError: Unexpected token P in JSON at position 0
    at JSON.parse (<anonymous>)
    at n.parseJSON 

2)当没有指定dataType时,我认为它假定XML:

Error: Invalid XML

服务器端:

public String exportSearchResults() throws Exception {

        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            log.error("Failed to write into response - fileName=" + filename + ", mimeType=" + mimeType, e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    return null;
}

struts.xml:

<action name="exportSearchResults" method="exportSearchResults" class="gov.nih.nci.cbiit.scimgmt.mcs.action.SearchRequestAction">
    <result type="json">
        <param name="contentType">text/plain</param>
    </result>           
    <result name="error">/WEB-INF/jsp/content/dashboardError.jsp
    </result>
</action>

标签: jqueryajaxdownloadstruts2struts

解决方案


推荐阅读