Angular $ http POST to target =" _blank" [英] Angular $http POST to target="_blank"
问题描述
我需要从Angular创建 POST
到URL ./ makeFile.php
这将创建一个文件使用基于 POST
数据中提供的信息的数据库查询中的内容。
I need to make a POST
from Angular to a URL ./makeFile.php
which will create a file with contents from a database query based on the information provided in that POST
data.
PHP强制浏览器打开一个保存对话框而不是仅显示这两行的响应:
PHP forces the browser to open a save dialog rather than just displaying the response with these 2 lines:
header('Content-Disposition: attachment; filename="' . $file_name . '.prj"');
echo $json;
但是使用<从AngularJS制作 POST
code> $ http 强制浏览器不打开此保存对话框:
But making a POST
from AngularJS using $http
forces the browser to not open this save dialog:
$http({
method: 'POST',
url: './makeFile.php',
data: {
project: ProjectService.getProject()
}
})
我无法生成 GET
因为URL的数据太长,否则我会用简单的 $ window.open('。/ makeFile.php','_ blank')$ c $替换它c>适用于(罕见的)小数据的情况。
I can't make a GET
because the data is too long for a URL, otherwise I would replace it with a simple $window.open('./makeFile.php', '_blank')
which works in (the rare) case of small data.
如何让Angular使这个 POST
到另一个窗口或让浏览器打开保存对话框?
How do I make Angular make this POST
to another window or let the browser open the save dialog?
修改:
正如Ivan建议的那样,我不得不以编程方式创建一个表单来实现我想要的。我是这样做的:
As Ivan suggested, I had to programatically create a form to achieve what I want. Here's how I did it:
JavaScript:
JavaScript:
var form = document.createElement('form');
form.action = './php/saveProject.php';
form.method = 'POST';
form.target = '_blank';
form.style.display = 'none';
var input = document.createElement('input');
input.type = 'text';
input.name = 'project';
input.value = angular.toJson(ProjectService.getProject(), false);
var submit = document.createElement('input');
submit.type = 'submit';
submit.id = 'submitProject';
form.appendChild(input);
form.appendChild(submit);
document.body.appendChild(form);
$('#submitProject').click();
document.body.removeChild(form);
PHP:
<?php
$project = get_magic_quotes_gpc() ? stripslashes($_POST['project']) : $_POST['project'];
// ...
header('Content-Disposition: attachment; filename="' . $file_name . '.prj"');
echo $json;
?>
推荐答案
我有类似的问题,我做不到使用 $ http
。所以我用 method =post
和 target =_ blank
以编程方式创建了html表单。我将隐藏的元素放在我需要发送的数据中。在我提交该表单后,我将其从dom中删除。
I had similar issue, and I couldn't do with with $http
. So I programatically created html form with method="post"
and target="_blank"
. And I placed hidden elements with data I needed to send. After I submitted that form I removed it from dom.
如果您找到另一种解决方案,请使用 $ http
告诉我。
Let me know if you find another solution, using $http
.
这篇关于Angular $ http POST to target =" _blank"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!