[英]Launch PHP function when button is pressed
我有一個php函數,將一些文本寫入本地文件...
<?php
function createtextfile()
{
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
}
?>
我試圖在單擊按鈕時啟動它,但是不確定如何最好地執行它。 我需要使用javascript還是有辦法完全使用PHP?
將createfile移至新的php文件,並使用ajax調用php文件
<a href="#" id="btn">Button</a>
<script>
$("#btn").click(function(e) {
$.ajax("createtextfile.php");
e.stopPropagation();
return false;
});
</script>
並在createfile.php中
$file = fopen("test.txt","w");
fwrite($file,"Hello World. Testing!");
fclose($file);
如果使按鈕成為表單的一部分,並發送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作為提交時調用的操作。
如果您使用表格,它將變得非常容易
您的html看起來像
<form method="GET/POST" action="yourphpscript.php">
whatever you wanna include in the form
<input type="submit" name="submit" value="submit"/>
</form>
然后使用php,您可以執行所需的操作,一旦找到單擊按鈕
<?php
if(isset($_POST['submit']))
{
do what you wanna do in here
}
?>
這是php的處理方式,對javascript不太確定
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.