如何从按钮调用php函数?

如何从按钮调用php函数?,php,Php,我有一个简单的php脚本: <?php $command = "git pull"; $output = shell_exec($command); echo "<pre>$output</pre>"; ?> 我想通过按下按钮来调用它: <form metod="post" action=""> <button name="button" type="submit">Pull changes<

我有一个简单的php脚本:

<?php
    $command = "git pull";
    $output = shell_exec($command);
    echo "<pre>$output</pre>";
?>

我想通过按下按钮来调用它:

<form metod="post" action="">
    <button name="button" type="submit">Pull changes</button>
</form>

<?php
    if(isset($_POST['button'])) {
        $command = "git pull";
        $output = shell_exec($command);
        echo "<pre>$output</pre>";
    }
?>

拉动变化

我想在按钮下面获得输出,或者用输出替换按钮,但我不想转到/pull.php,我只想运行脚本并获得输出。我该怎么做呢?

您需要使用javascript的XMLHTTPRequest(或者更好),在这两种情况下,javascript都可以让您从另一个url动态加载内容。

将action属性保留为空,并将代码放在按钮后,您将得到如下结果:

 <form onclick='run()'>
 <button type="submit">Pull changes</button>
 <div id='msg'><div/>
 </form>

拉动变化

PHP是一种服务器端语言,单击按钮是一种客户端操作,因此您需要使用JavaScript等客户端解决方案来弥补这一差距。

要使用ajax获得响应并在按钮下方显示,请先为按钮下方的消息留出空间:


拉动变化
现在在标题标记中添加以下内容:


函数运行()
{
loadXMLDoc(“pull.php”,function())
{
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
document.getElementById('msg')=xmlhttp.responseText;
}
});
}
函数loadXMLDoc(url,cfunc)
{
if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
onreadystatechange=cfunc;
open(“POST”,url,true);
xmlhttp.send();
}

仅使用php无法做到这一点,您需要使用AJAX。Javascript调用php。@fb1:“Javascript请求远程Web服务器调用php”为了清晰起见获胜。给自己买一本关于AJAX的书。这是一个太宽泛的问题,无法回答更多的问题。@Tomalak:是的,这一点非常清楚,直到执行完整的表单提交。我的解释是OP想要使用内联表单提交的“新热度”;正常压痕;解释而不是简单的代码转储;框架。
 <form onclick='run()'>
 <button type="submit">Pull changes</button>
 <div id='msg'><div/>
 </form>
 <script type="text/javascript">
 function run()
 {
 loadXMLDoc("pull.php",function()
 {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('msg') = xmlhttp.responseText;
    }
 });
 }
 function loadXMLDoc(url,cfunc)
 {
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=cfunc;
 xmlhttp.open("POST",url,true);
 xmlhttp.send();
 }
 </script>