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

查看:93
本文介绍了从同一文件中的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变量中的result变量中的JavaScript函数,并在警报框中显示(在这种情况下).

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'];
?>

注意

此示例使用了jQuery(第三方JavaScript包装器).我建议您首先对这些Web技术如何协同工作有一个更好的了解,然后再进一步使自己复杂化.

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天全站免登陆