从同一文件中的 HTML 表单调用 PHP 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5967322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a PHP function from an HTML form in the same file
提问by iTurki
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).
我首先想到的是使用表单。当用户提交表单时,会在同一个页面中执行一个 PHP 函数。用户不会被定向到另一个页面。处理将完成并显示在同一页面中(无需重新加载)。
Here is what I reach to:
这是我所达到的:
In the test.phpfile:
在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>
The PHP code [ test()
function] is in the same filealso:
PHP 代码 [ test()
function]也在同一个文件中:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
但是,我仍然遇到问题!有没有人有想法?
回答by Dutchie432
This cannot be done in the fashion you are talking about. PHP is server-sidewhile the formexists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
这不能以您所说的方式完成。PHP 是服务器端,而表单存在于客户端。如果您不想刷新页面,则需要考虑使用 JavaScript 和/或 Ajax。
test.php
测试文件
<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>
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.
它将调用getResult.php
并将序列化的表单传递给它,以便 PHP 可以读取这些值。任何getResult.php
回显都将返回到result
变量中的 JavaScript 函数test.php
并(在本例中)显示在警告框中。
getResult.php
获取结果.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
笔记
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.
此示例使用第三方 JavaScript 包装器 jQuery。我建议您先更好地了解这些 Web 技术如何协同工作,然后再将事情进一步复杂化。
回答by kapa
You have a big misunderstanding of how the web works.
你对网络的工作方式有很大的误解。
Basically, things happen this way:
基本上,事情是这样发生的:
- User (well, the browser) requests
test.php
from your server - On the server,
test.php
runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser - The browser displays the form, the user can interact with it.
- The user submits the form (to the URL defined in
action
, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
- 用户(好吧,浏览器)
test.php
从您的服务器请求 - 在服务器上
test.php
运行,里面的所有内容都被执行,结果 HTML 页面(包括你的表单)将被发送回浏览器 - 浏览器显示表单,用户可以与之交互。
- 用户提交表单(到 中定义的 URL
action
,在这种情况下是同一个文件),所以一切从头开始(除了表单中的数据也将被发送)。对服务器的新请求、PHP 运行等。这意味着页面将被刷新。
You were trying to invoke test()
from your onclick
attribute. This technique is used to run a client-sidescript, which is in most cases Javascript(code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Codingfor example.
您试图test()
从您的onclick
属性中调用。这种技术用于运行客户端脚本,在大多数情况下是Javascript(代码将在用户的浏览器上运行)。这与PHP无关,它是服务器端,驻留在您的服务器上,只有在请求进来时才会运行。例如,请阅读客户端与服务器端编码。
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
如果您想在不引起页面刷新的情况下执行某些操作,则必须使用 Javascript 在后台向服务器发送请求,让 PHP 执行它需要执行的操作,并从它接收响应。这种技术基本上称为AJAX,您可以使用 Google 找到大量关于它的优秀资源(如Mozilla 的精彩教程)。
回答by jenkin90
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
不重新加载,仅使用 HTML 和 PHP 是不可能的,但这可能与您想要的非常相似,但是您必须重新加载:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
回答by adorablepuppy
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
这是一个完整的 php 脚本,可以执行您所描述的操作,尽管毫无意义。您需要阅读服务器端与客户端。PHP 无法在客户端运行,您必须使用 javascript 与服务器交互,或者忍受页面刷新。如果您无法理解这一点,那么您将无法使用我的代码(或其他任何人的)来为您谋取利益。
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
以下代码在没有 jQuery 的情况下执行 AJAX 调用,并调用相同的脚本将 XML 流式传输到 AJAX。然后它会<br/>
在用户框下方的 div 中插入您的用户名和 a 。
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
在尝试像 AJAX 这样高级的东西之前,请先回去学习基础知识。你最终只会让自己感到困惑,并可能浪费别人的钱。
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
回答by Carlos Precioso
Use SAJAXor switch to JavaScript
使用SAJAX或切换到 JavaScript
Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.
Sajax 是一种开源工具,用于使使用 Ajax 框架(也称为 XMLHTTPRequest 或远程脚本)的网站编程尽可能简单。Sajax 可以轻松地通过 JavaScript 从您的网页调用 PHP、Perl 或 Python 函数,而无需执行浏览器刷新。
回答by Genjuro
in case you don't want to use Ajax , and want your page to reload .
如果您不想使用 Ajax 并且希望您的页面重新加载。
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
回答by ceejayoz
That's now how PHP works. test()
will execute when the page is loaded, not when the submit button is clicked.
这就是 PHP 的工作方式。test()
将在页面加载时执行,而不是在单击提交按钮时执行。
To do this sort of thing, you have to have the onclick
attribute do an AJAX call to a PHP file.
要执行此类操作,您必须让该onclick
属性对 PHP 文件执行 AJAX 调用。
回答by user3599285
Take a look at this example:
看看这个例子:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
回答by Jeff Lambert
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
您可以在不刷新页面的情况下提交表单,但据我所知,如果不使用对服务器上的 PHP 脚本的 JavaScript/Ajax 调用,这是不可能的。以下示例使用jQuery JavaScript 库。
HTML
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separatefile, btw). The data
above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET
super global. An example is below.
提交后,匿名 Javascript 函数将被调用,它只是向您的 PHP 文件发送请求(需要在单独的文件中,顺便说一句)。在data
上述需求是要发送到PHP文件的URL编码的查询字符串(基本上所有的表单字段的当前值)。这些将出现在您的服务器端 PHP 脚本的$_GET
超级全局中。下面是一个例子。
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
如果这是您的数据字符串,那么 PHP 脚本会将其视为:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
但是,您需要从表单字段构建数据,因为它们存在于您的表单中,例如:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
(您需要用“id”标记每个表单字段,上面的 id 是“user”。)
After the PHP script runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
PHP 脚本运行后,该success
函数被调用,PHP 脚本产生的任何和所有输出都将存储在变量中html
。
...
success: function(html) {
alert(html);
}
...
回答by John Mattan
This is the better way that I use to create submit without loading in a form.
这是我用来创建提交而不加载表单的更好方法。
You can use some CSS to stylise the iframe the way you want.
您可以使用一些 CSS 以您想要的方式设计 iframe。
A php result will be loaded into the iframe.
一个 php 结果将被加载到 iframe 中。
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>