从同一文件中的 HTML 表单调用 PHP 函数 [英] Calling a PHP function from an HTML form in the same file

查看:23
本文介绍了从同一文件中的 HTML 表单调用 PHP 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户输入文本并按下提交按钮后在同一页面中执行 PHP 函数.

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.

我首先想到的是使用表单.当用户提交表单时,会在同一个页面中执行一个 PHP 函数.用户不会被定向到另一个页面.处理将完成并显示在同一页面中(无需重新加载).

The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).

这里是我所达到的:

test.php 文件中:

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />
</form>

PHP 代码 [ test() 函数 ] 在同一个文件中也:

The PHP code [ test() function ] is in the same file also:

<?php
    function test() {
        echo $_POST["user"]; // Just an example of processing
    }
?>

但是,我还是遇到了问题!有人有想法吗?

However, I still getting a problem! Does anyone have an idea?

推荐答案

这无法以您所谈论的方式完成.PHP 是服务器端,而表单存在于客户端.如果您不想刷新页面,则需要考虑使用 JavaScript 和/或 Ajax.

This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.

<form action="javascript:void(0);" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" />
</form>

<script type="text/javascript">
    $("form").submit(function(){
        var str = $(this).serialize();
        $.ajax('getResult.php', str, function(result){
            alert(result); // The result variable will contain any text echoed by getResult.php
        }
        return(false);
    });
</script>

它将调用 getResult.php 并将序列化的表单传递给它,以便 PHP 可以读取这些值.任何 getResult.php 回显都将返回到 result 变量中的 JavaScript 函数,返回到 test.php 并且(在这种情况下)显示在一个警告框.

It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.

<?php
    echo "The name you typed is: " . $_REQUEST['user'];
?>

注意

此示例使用第三方 JavaScript 包装器 jQuery.我建议您先更好地了解这些网络技术如何协同工作,然后再将事情进一步复杂化.

This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.

这篇关于从同一文件中的 HTML 表单调用 PHP 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆