搜索表单提交数据和扁平化URLs

3
我有一个基于标签过滤文章的表单。用户可以访问example.com/news,使用POST数据提交要过滤的标签(例如tag1,tag2),这将重新加载页面以显示过滤后的文章,但URL仍然相同。
以下URL将返回相同的文章:example.com/news/tag1+tag2 两种方法都通过同一个控制器进行处理。我想让使用表单过滤标签的用户重定向到example.com/news/tag1+tag2 URL格式。
如何最好地实现这一点?是否应该将所有标签过滤请求发送到搜索控制器,然后创建一个重定向到example.com/news/tag1+tag2
2个回答

1

看起来你不应该基于过滤标签的初始提交进行任何搜索。如果你通过搜索控制器一次然后重定向,你最终会进行两次搜索。

如果用户提交标签以进行筛选,则仅使用这些标签构建URL并直接重定向到包含已过滤标签的URL。由于你说它进入相同的搜索控制器,因此将随后仅启动正确的搜索一次,并且用户的URL已经是你想要的最终结果。

因此,只需从$_POST中检索过滤标签,然后立即重定向到触发正确搜索的最终结果URL。

伪PHP

$valid_tags = array_filter($_POST['tags'], function($t) {
   // validate tags as alphanumeric (substitute the appropriate regex for your tag format)
   // this discards non-matching invalid tags.
   return preg_match('/^[a-z0-9]+$/i', $t);
});
// Don't forget to validate these tags in the search controller!
// Implode the tags (assuming they are received as an array) as a space separated string
// and urlencode() it
$tags = urlencode(implode(" ", $valid_tags));
header("Location: http://example.com/news/$tags");
exit();

0
$tags = 'tag1+tag2';
header ('Location: /news/' . $tags);
exit;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接