jQuery 在新窗口中显示 POST AJAX 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27030209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying POST AJAX Response in new window
提问by bryan
I send POST data through ajax using jQuery and it returns the binary data of a PDF file.
我使用 jQuery 通过 ajax 发送 POST 数据,它返回 PDF 文件的二进制数据。
I'd like to do something with this data. Either by providing a link to download, or opening it a new tab/window.
我想用这些数据做点什么。通过提供下载链接,或打开一个新选项卡/窗口。
I know sending a user to a website and using GET variables would be easier but there is a lot of data that gets sent through and it needs to be post.
我知道将用户发送到网站并使用 GET 变量会更容易,但是有很多数据需要发送,需要发布。
Is there a way I can take the data that I retrieve and let a user download / see it somehow?
有没有办法可以获取我检索的数据并让用户以某种方式下载/查看它?
$("#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"); }
});
});
回答by Larry Lane
I am assuming that you are able to retrieve the data and it is being stored in the data variable.
我假设您能够检索数据并且它被存储在数据变量中。
You might try the following in your success function:
您可以在成功函数中尝试以下操作:
//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);
Another option would be to dynamically create a div that is displayed using your success function in your $.ajax function.
另一种选择是动态创建一个使用 $.ajax 函数中的成功函数显示的 div。
Here is a jsfiddle that will help you if you want to experiment with it:
这是一个 jsfiddle,如果您想尝试它,它将为您提供帮助:
http://jsfiddle.net/larryjoelane/d8r3su0m/
http://jsfiddle.net/larryjoelane/d8r3su0m/
I have tested another way with the jquery $get function and it works for me. You just have to enable popups. here is the code I tested. I will attempt it with you ajax function when I get a chance.
我已经用 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);
});
});