用户是否可以在表单中输入值,然后在提交时将页面重定向到新页面,并将输入到表单中的值存储在PHP变量中?
这是我的表单代码;
<form id="loc-search" method="post">
<input type="text" id="search-by-location" name="custom-location" value="" placeholder="Sheffield, UK"/>
<input type="submit" id="submit" value=""/>
</form>
用户输入 #search-by-location
中的值后,页面需要重定向到weather.php
,该值存储在名为 $location
的 PHP 变量中
AJAX/JS不是我的强项,所以如果有人能指出我正确的方向,那就太好
将
参数action="weather.php"
添加到表单标签中。然后,当单击提交按钮时,您将被重定向到该页面。根据您的方法,在您的情况下POST
,输入值将在 PHP 的超全局$_POST
数组中可用。
在您的示例中,$location = $_POST["custom-location"];
就足够了。请注意,名称(而不是 ID)决定了目标 PHP 文档中的数组键。
不需要Javascript或AJAX来实现这一点。
这只是
一个普通的形式,所以为什么不在weather.php
页面上重定向后直接使用$_POST
:
$location = $_POST["custom-location"];
正如@Tacticus指出的,您还需要表单重定向(如果您尚未在JS中执行此操作)。通过在表单中添加action="weather.php"
:
<form id="loc-search" method="post" action="weather.php" >
...
</form>
如其他答案中所述,您应该修改表单,使其如下所示:
<form id="loc-search" method="post" action="weather.php">
<input type="text" id="search-by-location" name="custom-location" value="" placeholder="Sheffield, UK"/>
<input type="submit" id="submit" value=""/>
</form>
在你的 weather.php 文件中,你可以从 $_POST 全局变量中获取值,就像这样:
<?php
$location = $_POST["custom-location"];
//Interpret data
?>
请注意,您可以从表单 witch 已传递访问输入标签的值,以及输入的名称。在 html 中,您可以指定以下内容:
<input name="yourname" />
当您想要访问该值时,只需引用他的名字即可。
$_POST['yourname']
如果您使用 GET 方法让表单传递值,那么您也会这样做,只有值将存储在 $_GET 全局变量中,因此在使用 GET 方法的情况下,变量初始化将如下所示:
<?php
$location = $_GET["custom-location"];
//Interpret data
?>