我有一个根据标签过滤文章的表单。因此,用户可以访问 example.com/news
使用帖子数据提交要过滤的标签(例如 tag1、tag2),这会重新加载包含已过滤文章但 URL 相同的页面。
以下 url 将返回相同的文章:example.com/news/tag1+tag2
这两种方法都通过同一个 Controller 。我想让使用表单按标签过滤的用户重定向到 example.com/news/tag1+tag2
url 格式。
这样做的最佳方法是什么?是否会通过搜索 Controller 发送所有标签过滤器请求,然后创建到 example.com/news/tag1+tag2
的重定向?
最佳答案
似乎您不应该根据最初提交的过滤标签进行任何搜索。如果您通过搜索 Controller 一次然后重定向,您最终将进行两次搜索。
如果用户提交要过滤的标签,仅使用这些标签来构建 URL 并直接重定向到包含过滤标签的 URL。既然你说它进入同一个搜索 Controller ,它随后只会启动正确的搜索一次并且用户的 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();
关于php - 搜索表单发布数据和平面 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429718/