在javascript中访问codeigniter会话变量[关闭]

How to access codeigniter session variables inside javascript? If I create session variable inside plain php and access it in javascript it gives me result but in case of codeigniter session variables it gives me syntax error.

I use following code of line to access codeigniter session variable in my .js file

var m1  = "<?php echo json_encode($this->session->userdata('max_age')); ?>";
dpwqicw157673
dpwqicw157673 您需要向我们展示导致错误的所有代码,而不仅仅是您希望以某种方式工作的行。此外,translate.google.com可能会有所帮助。
8 年多之前 回复
doushengyou2617
doushengyou2617 好的。但它不起作用
8 年多之前 回复
duanjiati1755
duanjiati1755 输出的HTML是什么样的(在浏览器中)。如果PHP输出周围没有引号且输出为空,则保留varm1=;这会导致错误。
8 年多之前 回复
donglvmang8638
donglvmang8638 但我想访问javascript中的会话变量。有没有其他方法可以访问它?
8 年多之前 回复
doupacan2098
doupacan2098 所以告诉我们这一行。
8 年多之前 回复
duanjie6912
duanjie6912 如果我评论上面的代码,那么它将没有错误
8 年多之前 回复
doufu1950
doufu1950 你好DamienHirst下一行有正常的javascript代码
8 年多之前 回复
douying7289
douying7289 抱歉,在我的原始代码中没有引号。但它在下一行给出了语法错误。抱歉我的英语不好。我非常感谢所有给我建议的人。
8 年多之前 回复
dongshuzhuo5659
dongshuzhuo5659 如果这应该是一个JSON变量,您可能不希望该对象周围的引号。
8 年多之前 回复
duaner1634
duaner1634 下一行出错?那么,下一行是什么?
8 年多之前 回复
duanmaifu3428
duanmaifu3428 它给我下一行的语法错误
8 年多之前 回复
douyong6585
douyong6585 这对我来说是正确的。有什么问题?
8 年多之前 回复

2个回答

"I use following code of line to access codeigniter session variable in my .js file "


You cannot put PHP code inside your .js file. It will not be parsed. You must put your code in the PHP file that your .js file is being called from.

For example:

<script type="text/javascript">
var m1  = <?php echo json_encode($this->session->userdata('max_age')); ?>; 
</script>
<script type="text/javascript" src="script.js"></script>

As I mentioned in the comments above, the problem is most likely caused by an empty php echo output. You stated above that you DO NOT have quotes around your echo statement. So in your code it looks like this:

var m1  = <?php echo json_encode($this->session->userdata('max_age')); ?>; 

This might be a problem if your php variable $this->session->userdata('max_age') is empty. Because if that is the case, json_encode will output an empty string. Please do a "View Source" in your browser and look if that line looks like this:

var m1  = ;

If it does, you found your problem. The above is invalid and would cause the syntax error.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐