我需要在客户端的文件中写入一个字符串,但是出于安全考虑,Internet 协议(protocol)不允许这样做,这是我所做的解决方法:我有一个 AJAX 请求,它调用查询数据库的 JSP得到一个字符串。我需要向用户显示一个“另存为”对话框并将此字符串写入他们指定的本地路径。
我的 JavaScript 函数:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
在 JSP 中,我有这样的内容:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
当我收到警告说已获得结果时,我没有看到“另存为”对话框。这是我第一次这样做,请问我是否做错了什么?
但是,JavaScript 中是否有一种方法可以向用户显示“另存为”对话框并将“div”标记的内容写入客户端系统上的文件中?
最佳答案
使用常规 HTTP 请求,而不是 AJAX (XMLHttpRequest
) 请求。
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
这将发送 HTTP GET,而不是 POST,尽管看起来 GET 是此处使用的正确 HTTP 方法,因为您正在检索数据,但实际上并没有更改服务器上的任何内容。
关于javascript - 从 JSP 显示“另存为”窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10553757/