按下按钮(提交)并执行脚本

时间:2018-11-24 00:58:23

标签: php html

当变量($ fileName)不为空时-在页面上显示一个提交按钮。当按下时,我要执行脚本并使页面上的所有参数保持不变。

我的尝试

 if(empty($fileName) ) {
   echo "<td><form action='' method='POST'><INPUT TYPE='submit' name='download' VALUE='download'></form></td>\n";
   if (isset($_POST['download'])) {
     $SCRIPT=shell_exec("script.bash $a $b $c");
   }
 } else { echo " <td></td>\n "; }

结果应该是:启动脚本和页面保持不变(可以重新加载,但输入参数保持不变)。 但是现在页面已重新加载并清除所有值。

2 个答案:

答案 0 :(得分:1)

要实现您的目标,您需要使用表单页面中的Ajax来请求当前页面而无需重新加载。我建议您使用jQuery来正确实现它。此链接jQuery Ajax将演示如何使用表单发布而不重新加载页面。这部YouTube视频还可以帮助您:jQuery Ajax Tutorial

要记住的一件事是,如果要发送POST请求而不重新加载页面,则需要在启动功能时添加它:

$(".submit_button").click(function(e){

  e.preventDefault(); // This will disable the auto refresh after a form submit

  $.ajax({
    // Your Ajax Code...
  })

})

答案 1 :(得分:0)

您可以捕获post var,执行所需的操作并构建输出HTML,以根据需要填充输入。

<?php

// Assuming you are using PHP 7

$a = $_POST['a'] ?? null;
$b = $_POST['b'] ?? null;
$b = $_POST['c'] ?? null;
// Set up to add the value attributes as needed
// If any of the vars is missing, then it will be null
// so no value will be added to the HTML
$value_a = isset($_POST['a']) ? sprintf('value="%s"', $_POST['a']) : null;
$value_b = isset($_POST['b']) ? sprintf('value="%s"', $_POST['b']) : null;
$value_c = isset($_POST['c']) ? sprintf('value="%s"', $_POST['c']) : null;

if ( isset($_POST['download']) ) {
    $SCRIPT=shell_exec("script.bash $a $b $c");
}
?>
<form method="post">
<div><input type="text" name="a" <?= $value_a ?> ></div>
<div><input type="text" name="b" <?= $value_b ?>  ></div>
<div><input type="text" name="c" <?= $value_c ?>  ></div>
<div><input type="submit" name="download"></div>
</form>
相关问题