HTML 在提交时调用 PHP 函数而不离开页面

The*_*age 6 html php post

大家好

我试图通过将它们保存在服务器上的单独文件中来使我的一些 php 脚本可重用。

/public_html/scripts/phpfunctions.php

<?php echo 'This function has been called' ?>
Run Code Online (Sandbox Code Playgroud)

我有我的 HTML 表单

<form action="scripts/phpfunctions.php" method="post">
    <input type="text" name="user_input">
    <button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

现在该函数是一个单独的文件,它将浏览器导航到该文件,而不是在我当前的文件中执行脚本。

通常我会用 AJAX 解决这个问题并调用 php 函数而不是 php 页面。

是否可以在按下提交按钮后从 php 脚本内部调用 php 函数(它通常在如下页面中执行的方式)

<!DOCTYPE html>
<head><title>No Title</title></head>
<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
       echo 'function has been called'
    }
?>
<body>
    <form action="index.php" method="post">
        <input type="text" name="user_input">
        <button type="submit">Submit</button>
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 5

HTML 在提交时调用 PHP 函数而不离开页面

是的,只是不要使用action,表单将提交到当前页面。

<form method="POST">
    <!-- your input tags -->
</form>
Run Code Online (Sandbox Code Playgroud)

调用PHP函数,先检查是否提交,然后调用函数

if(isset($_POST['user_input'])){
   myFunction(); //here goes the function call
}
Run Code Online (Sandbox Code Playgroud)

是否可以在按下提交按钮后从 php 脚本内部调用 php 函数(它通常在如下页面中执行的方式)?

不,因为提交按钮是一个 HTML 元素,当你点击它时,你需要 JavaScript(例如通过 Ajax)将它发送到服务器 (PHP),然后服务器上的 PHP 页面可以执行所需的功能。

您可以使用类似<form method="POST" onsubmit="myJSFunction()">. myJSFunction()当您单击提交按钮时会调用JavaScript 函数,使用此函数您可以将所需的数据发送到服务器(例如通过 ajax)并在服务器上执行您的 PHP 函数。