我正在为我的项目使用codeigniter。要获得uri细分,我知道我可以使用
$this->uri->segment();
但我的情况有点不同
我的网址看起来像
localhost/mediabox/home/box/21
但是一旦我转到这个URL,就会出现一个弹出窗体,用户提供一个访问该页面的密钥,我使用ajax方法验证密钥,该方法位于我的家庭控制器validate_key函数内
当我回复网址时,它会给我localhost / home / validate_key
在调用家庭控制器的valiate_key时如何从url栏中的url wrritten获取21?
有什么想法吗?
由于
答案 0 :(得分:3)
这不是一个错误,这是一种自然的行为。
请考虑以下事项:
您通过在地址栏中输入网址从服务器请求validate_key
功能。 current_url()
返回localhost/blabla/validate_key
。 没有涉及AJAX。
使用AJAX请求validate_key
。将执行相同的PHP代码
current_url()
将更改为localhost/blabla/validate_key
即使您的浏览器地址栏显示localhost/blabla/box/21
。
那么,这意味着什么?这意味着Codeigniter base_url()
不关心您的地址栏,它关心它所处的功能,是否通过ajax
或正常请求调用。
所以只要这个函数被执行, URL指向它。
我对这种情况最喜欢的解决方案是简单地创建一个隐藏的输入。
简单地说,当用户请求box
功能时。你正在向他展示一个弹出窗体。所以添加一个hidden_input
字段,给它一个名字,值为21(取决于)。
例如(您应该根据您的具体需求定制):
将此内容添加到box
函数显示的视图中的表单中:
form_hidden("number", $this->uri->segment(3));
;
现在,这些数据将发送到您的validate_key
功能。我们如何访问它?这很简单!
function validate_key(){
$this->input->post("number");//returns 21 or whatever in the URL.
//OR if the form sends GET request
$this->input->get("number");//return 21 or whatever in the URL.
/*
*Or , you can do the following it's considered much safer when you're ONLY
*expecting numbers, since this function(intval) will get the integer value of
*the uri segment which might be a destructive string, so if it's a string
*this function will simply return 0.
*/
$number = intval($this->input->post("number"));//returns 21 or whatever in the URL.
//Or if it it GET request:
$number = intval($this->input->get("number"));//returns 21 or whatever in the URL.
}
答案 1 :(得分:0)
看起来您已使用.htaccess删除了网址的index.php
部分。因此,当您导航到localhost/mediabox/home/box/21
时,您将值21传递给名为box
的控制器中名为home
的函数
如果您想将该值保留在validate_key
函数中,请在调用时将其传递出去:
function box($param)
{
//$param = 21
$this->validate_key($param);
}
答案 2 :(得分:0)
它更好,建议使用隐藏字段并在需要时发布值。