问题
I've been using window.open to point to a php file where I create a pdf on the fly using fpdf and display it immediately to the user. Seems to work fine across all browsers and even mobile devices. For example:
window.open('/client/feature_Schedule/scheduleReport.php','Schedule_Report','width=900,height=600,status=yes');
I'm not passing any values in this example because all of the parameters needed already exist in the php file.
But now I'd like to pass values from javascript along in order to query of the database in the php file before creating the pdf and displaying it to the user. Is there a convention I should be aware of? Window.open doesn't seem to handle this except by adding the values after "?" at the end of the url. But I'd prefer to POST the values because there could be a lot of data being sent to the php file. I've even been playing around with $.ajax but am not sure how to trigger with pdf to open for the user.
Thanks.
回答1:
There is a solution to send POST data with window.open() and it is quite simple: Window.open and pass parameters by post method
It can even be made without any actual HTML code involved just with pure javascript programming.
// Edit: added javascript only solution:
<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>
回答2:
window.open()
can only perform GET requests. You will need to create a form with the appropriate controls and target if you want to have the same effect with POST instead.
回答3:
You could create a <form>
with hidden inputs and use JavaScript to submit the form. Notice the target="_blank"
attribute which causes the form to post to a new window.
<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>
来源:https://stackoverflow.com/questions/12029228/window-open-to-pass-parameters-to-php-and-trigger-pdf-creation-and-view