admin管理员组文章数量:1357219
I want to take the session data in .js file.Here i want the data in a function Now i'm directly put the value.How to take it from session.
.js file
function callAllfnt(){
get_data(1) ;
}
I want the 1 as session data.How to take it
I want to take the session data in .js file.Here i want the data in a function Now i'm directly put the value.How to take it from session.
.js file
function callAllfnt(){
get_data(1) ;
}
I want the 1 as session data.How to take it
Share Improve this question asked Feb 4, 2016 at 10:37 robinsrobins 1,6687 gold badges34 silver badges71 bronze badges 1-
PHP tag is not allowed in
.js
file. You have to useajax
for it. – Mr. Engineer Commented Feb 4, 2016 at 10:40
4 Answers
Reset to default 3If you want it on page load the try this:
function callAllfnt() {
var data = "<?php echo $_SESSION['givenName']; ?>";
}
In later part in the life cycle of the application, use AJAX
1)
View File
<script type="text/javascript">
var Sessionvalue = "<?php echo $this->session->userdata('session_name')";
<script>
After load your js file
<script src="<?php echo base_url(); ?>js/file.js" type="text/javascript"></script>
JS FILE
function callAllfnt() {
var data = SessionValue;
}
(OR)
2) Using Ajax call and Get the Session value
You need to create php script that will return Session data and call that with ajax like this:
php
if (isset($_GET['var'])) {
echo json_encode($_SESSION[$_GET['var']]);
}
js with jQuery:
function get_data(variable, callback) {
$.get('session.php', {'var':variable}, function(data) {
callback(data);
}, 'json');
}
and you can call that function using:
get_data(1, function(value) {
alert(value);
});
just use php tag with in single quotes if you java script is written in html page like
function callAllfnt() {
var value = '<?php echo $_SESSION["varName"]; ?>';
get_data(value) ;
}
But if your javascript code is written seperate js file then use ajax.
Third option is if your javascript file included in php file then create a javascript variable on top of js file including code and use that variable in js file.
本文标签: How to get the php session data in javascript function of a js fileStack Overflow
版权声明:本文标题:How to get the php session data in javascript function of a .js file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743985306a2571252.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论