Shorten URL by removing empty GET variables and simplifying variable names

余生长醉 提交于 2019-12-02 07:22:46

The parameter names come from the form's fields' name attributes.

So to make the form query for name=lorem+ipsum the input would have to look like this:

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

You should look at the name attributes, I'm guessing they are generated by some code you are using to create the code? The empty query parameters come from other input fields in the form. If you want full control of the query string, create the form by hand.

I recommend you following solution: First, you need to define html form with POST method:

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

Second, you need to define getSearchTerms action in your ExampleController:

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

Then, you need to define main search action:

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

Finally, you need to add a url-manager rule:

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

In this solution, getSearchTerms action is responsible for receiving user entered text, and then pass values to search action. Now your url can be http://localhost/example/search/sampleText . Note you can skip adding url-manager rule if you like. In this case, your url must be like http://localhost/example/search/name/sampleText. In fact, we can remove "name" part from url by adding url-manager rule.

Simple method, if jQuery is an option:

<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>
$('#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;
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!