카테고리 없음

[php] 버튼에서 PHP 함수를 호출하는 방법은 무엇입니까?

행복을전해요 2020. 12. 13. 21:23

You need to use javascript's XMLHTTPRequest (or better yet jQuery's get), in either case JavaScript will let you load content dynamically from another url.

-------------------

To use ajax to get the response and display it below the button, first make space for the message below the button:

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

now in the header tag add the following:

 <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>
                                                 
-------------------

PHP는 서버 측 언어이며 버튼 클릭은 클라이언트 측 작업이므로 JavaScript와 같은 클라이언트 측 솔루션을 사용하여 간격을 메워야합니다.

-------------------

action 속성을 비워두고 버튼 바로 뒤에 해당 코드를 넣으면 다음과 같이됩니다.

<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>";
                                    }
                                    ?>
                                    


출처
https://stackoverflow.com/questions/7415094