【问题标题】:Cakephp - Create a search field with a search buttonCakephp - 使用搜索按钮创建搜索字段
【发布时间】:2013-11-15 10:54:55
【问题描述】:

我需要按钮上的“onclick”操作,所以我会被重定向到这样的事情:

 location/[textfield_data]

我正在使用 cakephp,此时我到达的最近的是这个。

echo $this->Form->input('link', array('label' => false, "class" => "form-control input-medium", "placeholder" => __('Procurar')));

echo $this->Form->button('', array('class' => 'btn btn-primary icon-search icon-white' ,'onclick' => "location.href='/'"));

使用我的代码,cakephp 正在检索我:

/[view]?data%5Blink%5D=

[view] 是我所在的当前页面。

找到解决方案

我已经通过这种方式找到了解决方案。

echo $this->Form->input('link', array('label' => false, "class" => " form-control input-medium", "placeholder" => __('Procurar'), 'id' => 'search'));

echo $this->Form->button(null, array('class' => 'btn btn-primary icon-search icon-white' ,'onclick' => "location.href='/mywantedurl/'+document.getElementById('search').value;"));

请注意,我没有使用任何表单->创建或表单->结束,否则将无法正常工作。

【问题讨论】:

    标签: php forms cakephp search redirect


    【解决方案1】:

    为什么需要使用 JavaScript?只需使用 GET 方法。您应该使用GET 而不是POST 请求以任何方式进行搜索,因此可以为请求添加书签等。

    您可以使用$this->request->query 而不是$this->request->data 来实现此目的。

    <?php
    // app/View/Locations/index.ctp
    echo $this->Form->create('Location', array('type' => 'get'));
    echo $this->Form->input('Location.keywords');
    echo $this->Form->end('Search');
    

    然后在你对应的控制器中:

    <?php
    // app/Controller/LocationsController.php
    class LocationsController extends AppController {
    
        public function search() {
            if (!isset($this->request->query['keywords'])) {
                throw new BadRequestException();
            }
    
            $results = $this->Location->findByKeywords($this->request->query['keywords']);
    
            $this->set('results', $results);
        }
    }
    

    我不知道您的数据库表的实际架构或模型名称,但以上内容应该为您指明了正确的方向。

    【讨论】:

    • 感谢您的帮助,但我不想使用任何类型的 GET,因为我需要一个没有任何 url 编码的干净 url。
    • 如果它在 URL 中——作为查询字符串参数或段——那么无论如何它需要编码。
    【解决方案2】:

    我使用这样的代码

    echo $this->Form->input('link', array('label' => false, "class" => "form-control input-medium", "placeholder" => __('Procurar'), 'id' => 'search-field'));
    echo $this->Form->button('', array('class' => 'btn btn-primary icon-search icon-white' , 'id' => 'search-button'));
    $this->Js->get('#search-button');
    $this->Js->event('click', 'edit()');
    
    $this->Js->buffer
    (
        "function edit()
        {
            search_term = this.document.getElementById('search-field').value;
            if(search_term)
                window.location = \"/index.php/location/\" + search_term;
            return false;
        }"
    );
    

    【讨论】:

    • 感谢您的帮助,但是当我放置代码时,按钮没有反应,调试器中也没有 JS 错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多