简单的提交表单以转到页面

Simple submit form to go to a page

我有一些编号的页面:

1.php
2.php
3.php
etc.

我想创建一个用户输入任意数字的文本框:例如 2,然后按回车键或 Go 按钮,他们将转到 2.php 页面,具体取决于在输入的数字上。

我知道如何 link 到特定页面,如 form action="....",但我不确定如何回显用户输入并将其翻译为 link(是否使用 html 或 php).

例如:

<form method="POST">
<input type="number" value="" />
<input type="submit" value="Go" />
</form>

使用 PHP 你可以这样做:

<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
    // Redirect to the corresponding page
    header('Location: ' . $_POST['my_number'] . '.php');
}
?>

<form method="POST">
    <input name="my_number" type="number" value="" />
    <input type="submit" value="Go" />
</form>

您需要在表单中添加 action 属性,在数字输入中添加 name 属性。您的 action 属性中的文件将“捕获” POST 变量并执行重定向用户所需的逻辑。将您的表单标签更改为:

<form method="POST" action="redirect.php">
  <input type="number" value="" name="redirect" />
  <input type="submit" value="Go" />
</form>

然后创建 redirect.php 文件获取 POST 变量并进行重定向:

<?php

$redirectPage = (int) $_POST['redirect'];
$redirectUrl = "http://www.example.com/{$redirectPage}.php";
header("Location: $redirectUrl");
printf('<a href="%s">moved</a>.', $redirectUrl);

请注意,其中既没有输入验证也没有错误处理。

这类似于 DaMeGeX 的回答,但使用 javascript 转到新页面。

<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
    // Redirect to the corresponding page
    echo "<script> window.location.href = '".$_POST['number'].".php' </script>";
}
?>

<form method="POST">
    <input name="my_number" type="number" value="" />
    <input type="submit" value="Go" />
</form>

我认为,在您的情况下,最好的选择是使用客户端 javascript 根据输入的数字动态更改表单的 action 属性在输入框中。

完成此类任务的快速而肮脏的解决方案可能如下所示

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function submitAction(formElement) {
   var // get the input box element
       el = document.getElementById('form-action-number'),
       // get a number specified by user in the input box
       num = parseInt(el.value), 
       // validate that it's really a number and is greater than zero
       // (you don't want someone to request -666.php right? :)
       // build a page url using the correct number
       page = !isNaN(num) && num > 0 ? num.toFixed(0).toString() + '.php' : undefined;

   if (page) { // the page url is valid
      // set form's action attribute to an url specified by page variable
      formElement.setAttribute('action', page);
      // returning true will allow the form to be submitted
      return true; 
   }

   // you might think of a better way to notify user that the input number is invalid :)
   console.error('INVALID NUMBER SPECIFIED!');
   // returning false will prevent form submission
   return false;
}
</script>
</head>
<body>
  <!-- When user clicks Go, the return value of submitAction function will be used to decide if the form should be submitted or not -->
  <form method="POST" onsubmit="return submitAction(this)">
    <input id="form-action-number" type="number" value="" />
    <input type="submit" value="Go" />
  </form>
</body>
</html>