通过删除空GET变量并简化变量名来缩短URL

时间:2015-02-16 11:09:54

标签: php forms yii get

我在提交 GET表格后组成网址的网站上工作。表单值作为变量数组传递,其中必须至少定义一个变量才能使数据库上的搜索起作用。我希望通过删除空表单元素来缩短网址,并通过简化变量名称使其更加用户友好。

目前,网址看起来像这样(只有更多变量):

http://localhost/example/search?FormName[name]=lorem+ipsum&FormName[id]=&FormName[age]=&yt0=Search

我的目标是让它看起来像这样:

http://localhost/example/search?name=lorem+ipsum

为了做到这一点,我有以下问题:

  • 我已经读过在使用GET方法时不可能只用PHP删除空表单元素,因为这是html表单的标准行为。有没有办法用yii urlManager做到这一点?

  • 我可以将“FormName [name]”替换为更短的内容,例如“name”而不更改变量名称,例如使用正则表达式吗?

  • 最后但同样重要的是:“yt0 =搜索”是什么意思,我该如何从网址中删除它?

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

参数名称来自表格的字段' name属性。

因此要对name=lorem+ipsum进行表单查询,输入必须如下所示:

<form method="get" action="/example/search">
    <input type="text" name="name" value="lorem ipsum">
    <button type="submit">Search</button>
</form>

您应该查看name属性,我猜测它们是由您用于创建代码的某些代码生成的?空查询参数来自表单中的其他输入字段。如果要完全控制查询字符串,请手动创建表单。

答案 1 :(得分:1)

我建议您使用以下解决方案: 首先,您需要使用 POST 方法定义html表单:

<form method="post" action="/example/getSearchTerms">
    <input type="text" name="name" value="lorem ipsum">
    <button type="submit">Search</button>
</form>

其次,您需要在getSearchTerms中定义ExampleController操作:

public function actionGetSearchTerms()
{
    $this->render(Yii::app()->baseUrl.'/example/search/'.$_POST['name']);
}

然后,您需要定义主搜索操作:

public function search($name)
{
    //do search operation here.
}

最后,您需要添加网址管理器规则:

"example/search/<name>"=>"example/search"

在此解决方案中,getSearchTerms操作负责接收用户输入的文本,然后将值传递给搜索操作。现在您的网址可以是http://localhost/example/search/sampleText。请注意,如果您愿意,可以跳过添加url-manager规则。在这种情况下,您的网址必须与http://localhost/example/search/name/sampleText类似。实际上,我们可以通过添加url-manager规则从url中删除“name”部分。

答案 2 :(得分:1)

简单方法,如果jQuery是一个选项:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    (function($) {
        $('form').submit(function() { // ## Clean GET on Submit
            $('form input').each(function() { // ## Check each Input
                if ($(this).val().length == 0) { // ## If Empty
                    $(this).attr('disabled', true); // ## Disable Input
                }
            });
        });
    })(jQuery);
</script>

答案 3 :(得分:0)

$('#your-form').submit(function () {
    var data = $(this).serializeArray().filter(function (item) {
        return !!item.value;
    });
    var param = jQuery.param(data);
    window.location = this.action + (param ? "?" + param : "");
    return false;
});