亲爱的,我是codeigniter的菜鸟,
我想就如何创建一个搜索表单提出建议,该表单会产生以下网址:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
表单就像
<form action="http://domain/class/index">
<input name="searchvar1" value="searchvar1val">
<input name="searchvar2" value="searchvar2val">
<input type="submit">
</form>
最佳做法是什么?
我已经google了包括stackoverflow帖子,仍然无法找到任何解决方案。
谢谢:)
〜thisismyfirstposthere
更新 ::
我想强调一点,我的目标是处理来自uri字符串(上图)的搜索变量,而不是来自post vars;所以我认为将表单搜索设置为POST不是一个选项? :)
更新(2)
我不认为这可以在codeigniter中开箱即用,我想客户端使用jQuery将表单vars / vals处理成URI格式的表单操作。 完成后会在此处发布更新。
答案 0 :(得分:2)
查看user_guide:
$this->uri->assoc_to_uri()
将关联数组作为输入 并从中生成一个URI字符串。 数组键将包含在 串。例如:
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
我想如果您的表格是这样的:
<form action="http://domain/class/index/search">
<input name="product" value="shoes">
<input name="size" value="large">
<input name="color" value="red">
<input type="submit">
</form>
然后搜索控制器中的某处执行此操作$this->uri->assoc_to_uri($data);
恕我直言将生成product/shoes/size/large/color/red
答案 1 :(得分:1)
查看 - &gt;形式 - &gt; jquery,在表单提交:用action params替换action属性 - &gt;带有uri字符串的控制器 - &gt;其余的过程
jquery部分将是这样的
$("#searchFormID").submit(function(){
// $(this).serialize() outputs param1=value1¶m2=value2 string
// var.replace(regex, string) outputs param1/value1/param2/value2 string
// newact would be http://localhost/class/index/param1/value1/param2/value2
var newact = $(this).attr("action") + "/" + $(this).serialize().replace(/&|=/g,"/");
$(this).attr("action", newact); // or $(this).attr("target", newact);
return true;
});
注释:
答案 2 :(得分:0)
您可能需要enable query strings并使用$_GET
。 IMO,这是查询字符串的完美示例。
务必将表单更改为<form method="get" action="http://domain/class/index">
您的网址中会有一个查询字符串,如?searchvar1=value1&searchvar2=value2
您可以访问字符串的部分内容,如下所示:$this->input->get('searchvar1')
使用您当前使用的方法,如果用户搜索$config['permitted_uri_chars']
中不允许的任何字符,您将不得不自己进行大量编码和解码,以确保字符串是安全的/您的网址可读。 CI输入课为您解决了这个问题,因此这是我的建议。
基于URI段的搜索参数的另一个缺点是没有正确的方式来表达像?values[]=one&values[]=two&values[]=three
这样的数组。有一些黑客可以解决这个问题,但它们都是如此:黑客攻击。你最终会遇到麻烦。
使用$ _POST非常繁琐,并强制使用表单提交分页结果和链接,并确保您无法链接到搜索结果或正确使用后退按钮。
如果您必须使用此方法,只需将表单发布到您的控制器,阅读输入,然后redirect()
到您从中构建的URL。 littlechad在his answer
// This URL:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
// With this:
$search = $this->uri->uri_to_assoc();
// Produces this:
array(
'searchvar1' => 'searchvarval1',
'searchvar2' => 'searchvarval2',
);
// And you can use it like this:
$arg1 = $search['searchvar1'];
$arg2 = $search['searchvar2'];
要获得此网址,您可以使用表单发布此类内容(在发布后的控制器中):
$var1 = $this->input->post('searchvar1');
$var2 = $this->input->post('searchvar2');
redirect('searchvar1/'.urlencode($var1).'/searchvar2/'.urlencode($var2));
我确信你可以看到这比仅使用经过验证的查询字符串还要多得多......