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



我有一些编号的页面:

1.php
2.php
3.php
etc.

我想创建一个文本框,用户可以输入任何数字:例如2,然后点击回车或Go按钮,他们将根据输入的数字进入页面2.php

我知道如何链接到form action="...."中的特定页面,但我不知道如何回显用户输入并将其翻译为链接(无论是使用html还是php)。

例如:

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

您需要在表单中添加一个action属性,并在数字输入中添加name属性。来自动作属性的文件将";捕获";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);

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

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

一个快速而肮脏的解决方案来完成这样的任务可能看起来像这个

<!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>

使用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>

这与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>

最新更新