window.open将参数传递给php并触发pdf创建和查看

时间:2012-08-19 19:15:27

标签: php pdf post window.open

我一直在使用window.open指向一个php文件,我使用fpdf动态创建一个pdf并立即显示给用户。似乎可以在所有浏览器甚至移动设备上正常工作。例如:

window.open('/client/feature_Schedule/scheduleReport.php','Schedule_Report','width=900,height=600,status=yes');

我没有在这个例子中传递任何值,因为所需的所有参数已经存在于php文件中。

但是现在我想从javascript中传递值,以便在创建pdf并将其显示给用户之前在php文件中查询数据库。我应该注意一个公约吗? Window.open似乎没有处理这个,除非在“?”之后添加值在网址的末尾。但我更喜欢POST值,因为可能会有很多数据被发送到php文件。我甚至一直在玩$ .ajax,但我不确定如何触发pdf为用户打开。

感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用隐藏的输入创建<form>并使用JavaScript提交表单。请注意target="_blank"属性,该属性会导致表单发布到新窗口。

<a href="#" onclick="document.forms['pdfForm'].submit();return false;">Generate PDF</a>

<form target="_blank" id="pdfForm" name="pdfForm" method="POST">
    <input type="hidden" name="param1" value="val1" />
    <input type="hidden" name="param2" value="val2" />
</form>

答案 1 :(得分:2)

window.open()只能执行GET请求。如果您希望使用POST获得相同的效果,则需要create a form使用适当的控件和目标。

答案 2 :(得分:1)

有一个使用window.open()发送POST数据的解决方案,它非常简单: Window.open and pass parameters by post method

甚至可以在没有任何实际HTML代码的情况下进行纯javascript编程。

//编辑:添加了仅限javascript的解决方案:

<input type="button" value="Open" onclick="openWindow();" />
<script>
function openWindow(){
    // create <form>
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'process.php';
    form.target = 'window_1'; // target the window
    // append it to body
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(form);
    // create an element
    var child1 = document.createElement('input');
    child1.type = 'text'; // or 'hidden' it is the same
    child1.name = 'elem1';
    child1.value = 'some value';
    // append it to form
    form.appendChild(child1);
    // create another element
    var child2 = document.createElement('input');
    child2.type = 'text'; // or 'hidden' it is the same
    child2.name = 'elem2';
    child2.value = 'some other value';
    // append it to form
    form.appendChild(child2);

    // create window
    window.open('', 'window_1');

    // submit form
    form.submit();
    body.removeChild(form); // clean up
}
</script>