[英]Launch PHP function when button is pressed
I have a php function that writes some text to a local file... 我有一个php函数,将一些文本写入本地文件...
<?php
function createtextfile()
{
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
}
?>
I am trying to launch this when a button is clicked but am not sure how best to go about it. 我试图在单击按钮时启动它,但是不确定如何最好地执行它。 Would I need to use javascript or is there a way I can do it purely with PHP?
我需要使用javascript还是有办法完全使用PHP?
Move createfile to a new php file and call the php file with ajax 将createfile移至新的php文件,并使用ajax调用php文件
<a href="#" id="btn">Button</a>
<script>
$("#btn").click(function(e) {
$.ajax("createtextfile.php");
e.stopPropagation();
return false;
});
</script>
and inside createfile.php 并在createfile.php中
$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
You can do it purely using PHP and HTML if you make the button part of a form, and send POST / GET variables, then look for them in the PHP script; 如果使按钮成为表单的一部分,并发送POST / GET变量,然后在PHP脚本中查找它们,则可以纯粹使用PHP和HTML来完成此操作。
i.e.
<?php
if($_POST['submit'] == "Push Button!"){
//Do whatever
}else{
//Show the regular webpage.
?>
<form id="someForm" method="POST">
<input type="submit" id="submit" value="Push Button!">
</form>
<?php
}
?>
假装您正在制作HTML表单,并让您的php作为提交时调用的操作。
if you use a form it becomes really easy 如果您使用表格,它将变得非常容易
your html would look something like 您的html看起来像
<form method="GET/POST" action="yourphpscript.php">
whatever you wanna include in the form
<input type="submit" name="submit" value="submit"/>
</form>
then using php you can do what you need to, once you find out the button is clicked 然后使用php,您可以执行所需的操作,一旦找到单击按钮
<?php
if(isset($_POST['submit']))
{
do what you wanna do in here
}
?>
This is the php way of doing things, not too sure about javascript 这是php的处理方式,对javascript不太确定
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.