Yii2 URL管理器规则和带有GET方法的表格 [英] Yii2 URL manager rules and forms with GET method

查看:114
本文介绍了Yii2 URL管理器规则和带有GET方法的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局搜索表单,可以提交给控制器的搜索操作:

I have a global search form that submits to search action of a controller:

<?=Html::beginForm(['/feqh/search'], 'get', ['class' => 'navbar-form navbar-left', 'role' => 'search', 'id' => 'searchForm']);?>
        <div class="form-group has-feedback Right">
          <input id="q" type="text" class="form-control" placeholder="<?=yii::t('app','Search');?>" name="q" value="<?= Html::encode(\Yii::$app->getRequest()->getQueryParam('q',""));?>" />
          <i class="form-control-feedback glyphicon glyphicon-search"></i>
        </div>
              <button type="submit" class="btn btn-default"><?=yii::t('app','Submit');?> <i class="glyphicon glyphicon-ok"></i></button>
      </form>

我决定为规则搜索提供漂亮的URL,如下所示:

I decided to make pretty URL for search through rules as following:

'search/<q:\w+>' => 'feqh/search',

但是,提交表单始终会生成以下URL: example.com/feqh/search?q=anySearchString

However, submitting the form always generate the following URL: example.com/feqh/search?q=anySearchString

但是,可以访问example.com/search/anySearchString.这里是使用表单提交的问题.

However, example.com/search/anySearchString is accessible. Here the problem with submitting using the form.

我尝试更改表单操作网址:

I tried to change the form action URL:

<?=Html::beginForm(['feqh/search'],即删除开头的/,但没有任何区别.

<?=Html::beginForm(['feqh/search'] i.e removing the initial / but It does not make any difference.

顺便说一句,以下规则也有效:

By the way, the following rule is working too:

'search' => 'feqh/search',它使example.com/search?q=anySearchString. However, the applying of this rule prevent example.com/search/anySearchString`

'search' => 'feqh/search', it makes example.com/search?q=anySearchString. However, the applying of this rule preventexample.com/search/anySearchString`

推荐答案

这与您漂亮的URL配置无关(甚至与Yii无关)...这是浏览器.它只知道如何提交表单以GET或POST的形式发布.

This has nothing to do with your pretty URL configuration (and not even Yii)... It's a browser thing. It only knows how to submit a form is posted as either a GET or a POST.

因此,由于您是以GET模式发布的,因此只需将输入作为查询参数添加到您的URL中即可.

So since you are posting in GET mode it will simply add the inputs as query parameters to your URL.

如果您希望地址栏中的URL代表您的漂亮URL,您将必须控制提交并发出重定向?

If you want the URL in the address bar to represent your pretty URL you'll have to take control over the submit and perhaps issue a redirect instead?

$('#searchForm').submit(function() {
   window.location = $(this).attr("action") + '/' + $('#q').val();
   return false;
});

这是我现在能想到的唯一方法.

It's the only way I can think of right now.

这篇关于Yii2 URL管理器规则和带有GET方法的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆