首先,如果我的英语不好,请原谅我。我在使用 ajax 向 ExportServlet 发送数据时遇到一些问题。
ExportServlet.java
public class ExportServlet extends HttpServlet {
private static final long serialVersionUID = 6715605810229670146L;
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String fileName = req.getParameter("filename");
//Create ZIP file
try {
res.setContentType("applicatin/zip");
res.setStatus(HttpServletResponse.SC_OK);
ZipOutputStream zos = new ZipOutputStream(res.getOutputStream());
//Create TXT file
zos.putNextEntry(new ZipEntry(fileName + ".txt"));
zos.write(getOutputData());
zos.closeEntry();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] getOutputData() {
byte[] result = null;
String tmp = "Text file content";
result = tmp.getBytes();
return result;
}
}
上面的java代码绝对完美。
然后我有我的 ajax 代码,它将数据发送到我的 ExportServlet(我使用文件名作为示例):
//Post data to ExportServlet
$.ajax({
type: 'post',
url: '/export.zip',
data: "filename = myFile",
success:function(data){alert(data);},
error:function(){alert('error');}
});
问题是当ajax函数被触发时我得到一个错误回调。我还有一个下载 ExportServlet 生成的 ZIP 文件的链接:
<a href="/export.zip">Download file</a>
事实上,当我单击该链接时,我得到了其中包含“null.txt”的 ZIP 文件。我该如何解决这个问题?
提前非常感谢!
最佳答案
试试这个:
<a href="javascript:;" onclick="downloadFile();">Download file</a>
<div style="display: none;">
<iframe id="downloadFileFrame"></iframe>
</div>
function downloadFile() {
$('#downloadFileFrame').attr('src','/export.zip?filename=myFile');
return false;
}
关于java - 使用ajax将数据发送到java servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345799/