我的文件名是contacts.php,它有两个提交按钮;我想,如果插入按钮被按下,插入功能被调用,如果选择被按下,选择被调用。我已经写了以下代码:
//contacts.php
<?php
if(isset($_REQUEST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
但它不起作用。请帮助
<?php
if (isset($_REQUEST['insert'])) {
insert();
} elseif (isset($_REQUEST['select'])) {
select();
}
即使没有单击按钮,您的代码也会调用insert()
,这将在页面首次显示时发生。
使用post方法,因为它是安全的
//contacts.php
<?php
if(isset($_POST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
如果在函数内部使用return
返回结果,则在调用函数时必须使用echo打印结果。
if(isset($_REQUEST['select']))
{
echo select();
}
elseif(isset($_REQUEST['insert']))
{
echo insert();
}
正如几个人所描述的(总结前面的评论),您有两个选项。
第一种是通过POST或GET直接将数据发送到服务器,并根据select()和insert()中的操作保留(刷新)页面。
虽然这不是讨论POST与GET的合适位置,但惯例是在向服务器发送数据时使用POST。POST稍微安全一些,因为信息没有存储在浏览器中。点击此处了解更多关于这两个的信息:http://www.w3schools.com/tags/ref_httpmethods.asp
第二种选择是使用AJAX在不刷新网页的情况下完成任务。简而言之,AJAX使用放置在页面上的Javascript方法与服务器通信,从而避免了服务器上的PHP实际更改页面上的任何内容(这需要刷新)。AJAX的代码示例可以在这里找到:http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
<?php
$insert = $_POST['insert'];
$select = $_POST['select'];
if ($insert) {
insert();
}
if ($select) {
select();
}
else {
echo 'press any button...';
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select() {
echo 'you pressed the [select] button';
exit;
}
function insert() {
echo 'you pressed the [insert] button';
exit;
}
?>