Simple Search: Passing Form Variable to URI Using CodeIgniter

前端 未结 5 1202
旧巷少年郎
旧巷少年郎 2021-02-06 17:49

I have a search form on each of my pages. If I use form helper, it defaults to $_POST. I\'d like the search term to show up in the URI:

http://examp         


        
相关标签:
5条回答
  • 2021-02-06 18:09

    Check out this post on how to enable GET query strings together with segmented urls.

    http://codeigniter.com/forums/viewthread/56389/#277621

    After enabling that you can use the following method to retrieve the additional variables.

    // url = http://example.com/search/?q=text
    $this->input->get('q');
    

    This is better because you don't need to change the permitted_uri_chars config setting. You may get "The URI you submitted has disallowed characters" error if you simply put anything the user enters in the URI.

    0 讨论(0)
  • 2021-02-06 18:09

    I don't know much about CodeIgniter, but it's PHP, so shouldn't $_GET still be available to you? You could format your URL the same way Google does: mysite.com/search?q=KEYWORD and pull the data out with $_GET['q'].

    Besides, a search form seems like a bad place to use POST; GET is bookmarkable and doesn't imply that something is changing server-side.

    0 讨论(0)
  • 2021-02-06 18:14

    As far as I know, there is no method of accomplishing this with a simple POST. However, you can access the form via Javascript and update the destination. For example:

    <form id="myform" onsubmit="return changeurl();" method="POST">
    <input id="keyword">
    </form>
    
    <script>
    function changeurl()
    {
        var form = document.getElementById("myform");
        var keyword = document.getElementById("keyword");
    
        form.action = "http://mysite.com/search/"+escape(keyword.value);
    
        return true;
    }
    </script>
    
    0 讨论(0)
  • 2021-02-06 18:28

    There's a better fix if you're dealing with people without JS enabled.

    View:

    <?php echo form_open('ad/pre_search');?>
       <input type="text" name="keyword" />
    </form>
    

    Controller

    <?php
        function pre_search()
        {
            redirect('ad/search/.'$this->input->post('keyword'));
        }
    
        function search()
        {
            // do stuff;
        }
    ?>
    

    I have used this a lot of times before.

    0 讨论(0)
  • 2021-02-06 18:31

    Here is the best solution:

    $uri = $_SERVER['REQUEST_URI'];
    
    $pieces = explode("/", $uri);
    
    $uri_3 = $pieces[3];
    

    Thanks erunways!

    0 讨论(0)
提交回复
热议问题