javascript 在 codeigniter 中有条件地设置会话数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11947746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditionally set session data in codeigniter
提问by Nishant Jani
i want to set my session data in my view but Conditionally, so in javascript portion of my view i have
我想在我的视图中设置我的会话数据,但有条件地,所以在我的视图的 javascript 部分我有
$('#demo').click(function(){
$this->session->set_userdata('sample',10);
});
However , whenever i refresh my page , without clicking the button , the session data , "sample" is set, is there a way i can get this session data set ONLY after i click the button ?
但是,每当我刷新页面时,不单击按钮,会话数据“示例”已设置,有没有办法仅在单击按钮后才能获取此会话数据集?
Thank you
谢谢
回答by Fran Verona
You're mixing Javascript and PHP (client-side and server-side). You can do it by using Ajax like this:
您正在混合使用 Javascript 和 PHP(客户端和服务器端)。您可以像这样使用 Ajax 来做到这一点:
$('#demo').click(function(){
$.ajax({
type: "POST",
url: "mycontroller/sessions"
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
And in your Mycontroller.php
file, you should create a function called "sessions":
在您的Mycontroller.php
文件中,您应该创建一个名为“会话”的函数:
function sessions(){
$this->session->set_userdata('sample',10);
}
If you need to pass information from Javascript to PHP:
如果您需要将信息从 Javascript 传递到 PHP:
var dummy = 10;
$('#demo').click(function(){
$.ajax({
type: "POST",
url: "mycontroller/sessions",
data: { value: dummy }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
function sessions($value){
$this->session->set_userdata('sample',$value);
}
More information about Ajax in JQuery http://api.jquery.com/jQuery.ajax/
有关 JQuery 中 Ajax 的更多信息http://api.jquery.com/jQuery.ajax/
EDIT:
编辑:
To check if a session variable exists in CodeIgniter:
要检查 CodeIgniter 中是否存在会话变量:
function sessions(){
$sId = $this->session->userdata('session_id');
if(isset($sId)){
// session_id exist
}
}
Section "Retrieving Session Data" http://codeigniter.com/user_guide/libraries/sessions.html
“检索会话数据”部分http://codeigniter.com/user_guide/libraries/sessions.html
回答by tGilani
The following method returns FALSE if variable in session is not set
如果未设置会话中的变量,则以下方法返回 FALSE
$this->session->userdata('sample')
Otherwise it returns the appropriate value.
否则它返回适当的值。