【问题标题】:How to submit a form by appending textbox value to URL in PHP?如何通过将文本框值附加到 PHP 中的 URL 来提交表单?
【发布时间】:2018-07-06 14:45:49
【问题描述】:

我有一个包含文本框和提交按钮的 HTML 表单。当我提交表单时,我希望将文本框值附加到 URL。

例如,如果我的域是 http://www.example.com/ 并且表单位于 index.php 上。假设文本框值为“test”,那么当提交表单时,URL 应更改为http://www.example.com/test。我们如何实现它?

HTML 代码:

<form method="post" action="">
    <input type="text" name="txtname" value="<?php echo $name; ?>" />
    <input type="submit" name="btnsubmit" value="Submit" />
</form>

PHP 代码:

<?php
$name = NULL;

if(isset($_POST['btnsubmit']))
{
    $name = $_POST["txtname"];
}
?>

.htaccess 代码:

# .htaccess mod_rewrite
# example.com

#Enable mod rewrite
Options +FollowSymlinks -MultiViews
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

【问题讨论】:

  • 这种方法的意义何在?
  • @u_mulder 也许是维基百科“转到文章”框的近似值?但在这种情况下,最好提交表单并让服务器将您重定向到正确的页面(如果存在),或者有用的错误页面(如果不存在)...
  • @NiettheDarkAbsol 你猜对了,但事实并非如此。
  • @u_mulder 我想这样做是因为我想以 SEO 友好的方式与文本框值共享 URL,而不是与 GET 查询字符串。

标签: php


【解决方案1】:

jQuery 解决方案怎么样?比如……

$(document).ready(function(){
	var txtname = $('#txtname').val();
	var url = window.location.href;
	var new_url = url + "/" + txtname;
		
	$('#formid').on('submit', function(e){
			e.preventDefault();
			// Do what you need to do here.
			console.log(new_url);
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formid" method="post" action="">
  <input id="txtname" type="text" name="txtname" value="testname" />
	<input type="submit" name="btnsubmit" value="Submit" />
</form>

【讨论】:

  • 但是页面没有接收到表单文本框的值。我也想在文本框中保留提交的值。当我尝试通过 PHP 接收文本框值时,我收到了 Notice: Undefined index: txtname in ...
  • 如果您遇到该错误,您需要在提交帖子之前设置您的 textname 变量。请参阅上面我编辑的答案。
【解决方案2】:

你可以使用标题:

$name = $_POST['txtname'];
header('Location: http://www.example.com/$name');

如果你想得到没有错误的值,你可以像这样将变量设置为空:

$name = isset($_POST['txtname']) ? $_POST['txtname'] : '';

将其放在您的开始 php 标记之后。

【讨论】:

  • 但我不想重定向。
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多