如何通过单击按钮调用PHP函数我创建了一个名为functioncalling.php的页面,其中包含两个按钮:Submit和Insert。作为PHP的初学者,我想测试单击按钮时执行的功能。我希望输出出现在同一页面上。所以我创建了两个函数,每个按钮一个。functioncalling.php的源代码如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
<body>
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<?php function select(){
echo "The select function is called.";
}
function insert(){
echo "The insert function is called.";
}
?>这里的问题是在点击任何按钮后我没有得到任何输出。我到底哪里错了?
3 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
按钮单击是客户端,而PHP是在服务器端执行,但您可以使用Ajax实现此目的:
$('.button').click(function() { $.ajax({ type: "POST", url: "some.php", data: { name: "John" } }).done(function( msg ) { alert( "Data Saved: " + msg ); });});
在您的PHP文件中:
<?php function abc($name){ // Your code here }?>
慕丝7291255
TA贡献1859条经验 获得超6个赞
是的,你需要Ajax。有关详细信息,请参阅以下代码。
像这样更改你的标记
<input type="submit" class="button" name="insert" value="insert" /><input type="submit" class="button" name="select" value="select" />
jQuery的:
$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'ajax.php', data = {'action': clickBtnValue}; $.post(ajaxurl, data, function (response) { // Response div goes here. alert("action performed successfully"); }); });});
在ajax.php中
<?php if (isset($_POST['action'])) { switch ($_POST['action']) { case 'insert': insert(); break; case 'select': select(); break; } } function select() { echo "The select function is called."; exit; } function insert() { echo "The insert function is called."; exit; }?>
临摹微笑
TA贡献1982条经验 获得超2个赞
您应该使按钮调用相同的页面,并在PHP部分中检查按钮是否被按下:
HTML:
<form action="theSamePage.php" method="post"> <input type="submit" name="someAction" value="GO" /></form>
PHP:
<?php if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction'])) { func(); } function func() { // do stuff }?>
- 3 回答
- 0 关注
- 1647 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消