How to make dynamic form action address in codeign

2019-01-20 02:26发布

问题:

I have a search form on my site, and it looks like this:

<form action="/search/results">
<input type="text" name="keyword">
<button type="submit">  // etc...
</form>

It gets me into mysite.com/search/results/ page where I process post parameters. Of course, I can use the GET method, and then it will be

/search/results?keyword="some_keyword",

but is it possible to make the result page URL look like

mysite.com/search/results/keyword

回答1:

I would use jQuery

$('#myform').submit(function(){
    $(this).attr('action', $(this).attr('action') + "/" + $(this).find(input[name="keyword"]).val());
});

Another possibility is to make a proxy method in your controller, it's useful if you want to have all your post values in the url:

public function post_proxy() {
    $seg1 = $this->input->post('keyword');
    $seg2 = $this->input->post('keyword2');
    $seg3 = $this->input->post('keyword3');

    redirect('my_method/'.$seg1.'/'.$seg2.'/'.seg3);
}

In that case I would use arrays in post data to simplify code:

<input type="text" name="kw[1]">
<input type="text" name="kw[2]">
<input type="text" name="kw[3]">

$segment_array = $this->input->post('kw');
$segments = implode("/", $segment_array);
redirect('my_method'.$segments);