我使用 jQuery 通过 ajax 发送 POST 数据,它返回 PDF 文件的二进制数据。
我想用这些数据做点什么。通过提供下载链接或打开新选项卡/窗口。
我知道将用户发送到网站并使用 GET 变量会更容易,但是发送的数据很多,需要发布。
有没有办法可以获取我检索到的数据并让用户以某种方式下载/查看它?
$("#export_pdf").click(function()
{
var data_serialize = "v1=blah&var2=again&var3=more_info",
url = "/actions/export-pdf";
$.ajax({
type: "POST",
url: url,
data: data_serialize,
success: function(data)
{
// data = PDF binary
// I want to do something with this
},error: function(data) { alert("error"); }
});
});
最佳答案
我假设您能够检索数据并且它存储在数据变量中。
您可以在成功函数中尝试以下操作:
//open a new window note:this is a popup so it may be blocked by your browser
var newWindow = window.open("", "new window", "width=200, height=100");
//write the data to the document of the newWindow
newWindow.document.write(data);
另一个选择是动态创建一个 div,使用 $.ajax 函数中的 success 函数来显示。
如果您想尝试一下,这里有一个 jsfiddle 可以帮助您:
http://jsfiddle.net/larryjoelane/d8r3su0m/
我已经使用 jquery $get 函数测试了另一种方法,它对我有用。您只需启用弹出窗口即可。这是我测试的代码。当我有机会时,我会尝试使用你的ajax函数。
$("#load_pdf").on("click",function(){
//swap url with a pdf file you have access to for testing
var url = "http://localhost/Responder Manual.pdf";
$.get(url,function(data){
//open a new window note:this is a popup so it may be blocked by your browser
var newWindow = window.open("", "new window", "width=200, height=100");
//write the data to the document of the newWindow
newWindow.document.write(data);
});
});
关于jquery - 在新窗口中显示 POST AJAX 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27030209/