Mik*_*ens 7 javascript php jquery submit preview
我正在使用表单将信息发送到php页面.(使用'GET')我想在表单下面有两个按钮:一个用于预览生成的页面,另一个用于下载生成的页面.
我找到了预览部分的解决方案:
<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>
Run Code Online (Sandbox Code Playgroud)
哪个效果很好.
为了使生成的页面可供下载,我通常使用普通的提交按钮:
<input type="submit"
name="submit"
id="submit"
onClick="myFunction()"
value="Download Bonus Page" >
Run Code Online (Sandbox Code Playgroud)
在生成的php页面上,我在最顶部添加了
<?php
$filename = 'bonuspage.html';
header('Content-disposition: attachment; filename=' . $filename);
header('Content-type: text/html');
// ... the rest of your file
?>
Run Code Online (Sandbox Code Playgroud)
我想知道如何将两种功能结合起来,因为当我点击任一按钮时,它始终是打开的预览 - 我无法让下载工作......
小智 0
像这样放置两个按钮:
<script type="text/javascript">
function myFunction(el) {
$(el).parents('form').first().attr('target','_blank').find('input[name="what"]').val('download');
}
</script>
<form method="GET">
<input type="hidden" name="what" value="preview" />
<input type="submit" value="Preview" />
<input type="button" value="Download" onclick="myFunction(this)" />
</form>
Run Code Online (Sandbox Code Playgroud)
这样,您将获得一个名为what指示按下了哪个按钮的附加变量。
在你的 PHP 文件中,只需执行以下操作:
<?php
$filename = '/complete/path/of/the/file.html';
if($_GET['what'] === 'preview') {
//
} else {
header('Content-disposition: attachment; filename=' . basename($filename));
header('Content-type: text/html');
}
echo file_get_contents($filename);
?>
Run Code Online (Sandbox Code Playgroud)
还有另一种方法,有两个具有名称和不同值的提交按钮,您可以在 PHP 脚本中测试它,但您仍然需要使用 Javascripttarget="_blank"下载。
更好的方法是使用 HTML5<a download>语法。检查此链接。