【发布时间】:2014-04-08 10:54:06
【问题描述】:
实现php代码运行时的最佳方式是什么
按下/单击按钮。做了一些研究,但除了几个显示使用 JavaScript 的例子之外,找不到任何相关的东西。
我希望它纯粹是在 PHP 中。
在这个精确的时刻,我以以下方式创建了按钮 <input type='button' value='Click Me'/> 现在不知道该怎么做。谁能帮忙。
【问题讨论】:
实现php代码运行时的最佳方式是什么
按下/单击按钮。做了一些研究,但除了几个显示使用 JavaScript 的例子之外,找不到任何相关的东西。
我希望它纯粹是在 PHP 中。
在这个精确的时刻,我以以下方式创建了按钮 <input type='button' value='Click Me'/> 现在不知道该怎么做。谁能帮忙。
【问题讨论】:
我认为您不能仅通过本机 HTML 运行 PHP 脚本。使用 JavaScript 将是您能做的最简单的解决方案。
【讨论】:
表单和 php 的基础知识。当按钮被按下时,表单会调用一个动作(某些页面,甚至它本身)。然后 php 检查按钮是否被按下。如果是,做点什么,如果不是,忽略它。虽然不是创建按钮,提交会更好,但按钮工作得很好。
<form method="post" action="./PHPScripts.php" />
<input type='button' value='Click Me' name='button' /> <-- added a name
<input type='submit' value='Click Me' name='submitButton' />
<input type='submit' value='Click Me' name='submitButton2' />
</form>
// below would be on the page called by the action in the above form
// which can be on the same page with no problem, but larger amounts of
// code become more difficult to read, so having multiple files is recommended
<?php
if($_POST['button']) {
// php code (either execute it, or call function)
}
if($_POST['submitButton']) {
// php code (either execute it, or call function)
}
if($_POST['submitButton2']) {
// php code (either execute it, or call function)
}
?>
如果在同一页面上,最好将 php 代码放在 html 的顶部,但出于演示的原因,我将其放在底部。 (更容易阅读)
【讨论】:
想法是,您需要为按钮赋予 name 属性。根据表单的提交方式,在这种情况下,提交给它自己或由表单 action 属性和方法确定的另一个页面,然后脚本将运行。
<form action="submit.php" method="post">
<input type='button' value='Click Me' **name="submit"**/>
</form>
if(isset($_POST['submit']) {
//runs when the button is clicked
}
【讨论】:
<form action="index.php" method="post">
<input type='button' name='btn_func' value='Click Me'/>
</form>
<?php
if(isset($_POST['btn_func'])){
//call the function here.
}
?>
如果你有 10 个按钮:
<form action="index.php" method="post">
<input type='button' name='btn_func_1' value='Click Me 1'/>
<input type='button' name='btn_func_2' value='Click Me 2'/>
<input type='button' name='btn_func_3' value='Click Me 3'/>
<input type='button' name='btn_func_4' value='Click Me 4'/>
<input type='button' name='btn_func_5' value='Click Me 5'/>
<input type='button' name='btn_func_6' value='Click Me 6'/>
<input type='button' name='btn_func_7' value='Click Me 7'/>
<input type='button' name='btn_func_8' value='Click Me 8'/>
<input type='button' name='btn_func_9' value='Click Me 9'/>
<input type='button' name='btn_func_10' value='Click Me 10'/>
</form>
<?php
if(isset($_POST['btn_func_1'])){
//call the function here.
}
?>
或者使用条件/切换语句。
【讨论】:
如果您打算使用input type="button",我假设您需要JavaScript 来处理点击事件?然后向 PHP 文件或其他东西发出 Ajax 请求?
或者,您可以将输入类型从“按钮”更改为“提交”<input type="submit" name="submitButton" id="submitButton" value="Submit" />
然后...最简单的(因为没有更好的词)是在页面顶部检查提交帖子变量。如果它在那里,PHP 将处理它。或者,如果没有设置变量,它会显示表单。
<?php
if (isset($_POST['submitButton']))
{
// form has been submitted.
// do something with PHP.
}
?>
<form action="file.php" method="post">
...
<input type="submit" name="submitButton" id="submitButton" value="Submit" />
</form>
【讨论】: