How to access PHP session variables from jQuery function in a .js file? In this code, I want to get "value" from a session variable
如何从.js文件中的jQuery函数访问PHP会话变量?在这段代码中,我想从会话变量中获取“值”
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
7 个解决方案
#1
51
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
您可以通过PHP生成javascript文件。没有什么说javascript文件必须有.js扩展名。例如,在您的HTML中:
<script src='javascript.php'></script>
Then your script file:
然后你的脚本文件:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
如果这个特定方法不是一个选项,你可以在你的javascript文件中放入一个AJAX请求,并从服务器端脚本中将数据作为JSON返回。
#2
11
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
我正在努力解决同样的问题,偶然发现了这个页面。我想出的另一个解决方案是:
In your html, echo the session variable (mine here is $_SESSION['origin']
) to any element of your choosing : <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
在你的html中,将会话变量(我的这里是$ _SESSION ['origin'])回显给你选择的任何元素:
<?= $ _ SESSION ['origin'];?>
In your js, using jQuery you can access it like so : $("#sessionOrigin").text();
在你的js中,你可以使用jQuery来访问它:$(“#sessionOrigin”)。text();
EDIT: or even better, put it in a hidden input
编辑:甚至更好,把它放在一个隐藏的输入
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
”>
#3
7
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.
如果你想保持更清晰的PHP和JS分离(它使IDE中的语法高亮和检查更容易),那么你可以为你的代码创建jquery插件,然后将$ _SESSION ['param']作为变量传递。
So in page.php:
所以在page.php中:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
然后在my_progress_bar.js中:
(function ($) {
$.my_progress_bar = function(percent) {
$( "#progressbar" ).progressbar({
value: percent
});
};
})(jQuery);
#4
2
You can pass you session variables from your php script to JQUERY using JSON such as
您可以使用JSON将会话变量从php脚本传递给JQUERY
JS:
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe@jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
#5
1
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
您无法在JS中访问PHP会话变量/值,一个是服务器端(PHP),另一个是客户端(JS)。
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
您可以做的是将SESSION值传递给JS,例如,通过AJAX调用。在你的JS中,调用一个PHP脚本,它只是输出以返回给你的SESSION变量的值,然后使用你的JS来处理这个返回的信息。
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
或者将值存储在COOKIE中,可以通过任一框架访问它。虽然这可能不是您情况下的最佳方法。
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
或者你可以在PHP中生成一些返回/设置变量的JS,即:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
#6
0
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
严格来说,这并不是使用jQuery,但我发现这种方法比使用jQuery更容易。在这里可能有无穷无尽的方法来实现这个和许多聪明的方法,但并非所有方法都适用于我。但是,以下方法始终有效,我将其传递给万一以防万一。
Three javascript libraries are required, createCookie
, readCookie
and eraseCookie
. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
需要三个javascript库,createCookie,readCookie和eraseCookie。这些图书馆不是我的,但是大约5年前我开始使用它们并且不知道它们的起源。
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
要调用它们,您需要创建一个小PHP函数,通常作为支持库的一部分,如下所示:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
因此,要使用所有你现在必须包含在index.php文件中
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
现在在您的javascript library.js中,您可以使用以下代码恢复cookie:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
我希望这有帮助。
#7
0
Strangely importing directly from $_SESSION not working but have to do this to make it work :
奇怪地从$ _SESSION直接导入不起作用但必须这样做才能使其工作:
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
并在to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file
#1
51
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
您可以通过PHP生成javascript文件。没有什么说javascript文件必须有.js扩展名。例如,在您的HTML中:
<script src='javascript.php'></script>
Then your script file:
然后你的脚本文件:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
如果这个特定方法不是一个选项,你可以在你的javascript文件中放入一个AJAX请求,并从服务器端脚本中将数据作为JSON返回。
#2
11
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
我正在努力解决同样的问题,偶然发现了这个页面。我想出的另一个解决方案是:
In your html, echo the session variable (mine here is $_SESSION['origin']
) to any element of your choosing : <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
在你的html中,将会话变量(我的这里是$ _SESSION ['origin'])回显给你选择的任何元素:
<?= $ _ SESSION ['origin'];?>
In your js, using jQuery you can access it like so : $("#sessionOrigin").text();
在你的js中,你可以使用jQuery来访问它:$(“#sessionOrigin”)。text();
EDIT: or even better, put it in a hidden input
编辑:甚至更好,把它放在一个隐藏的输入
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
”>
#3
7
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.
如果你想保持更清晰的PHP和JS分离(它使IDE中的语法高亮和检查更容易),那么你可以为你的代码创建jquery插件,然后将$ _SESSION ['param']作为变量传递。
So in page.php:
所以在page.php中:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
然后在my_progress_bar.js中:
(function ($) {
$.my_progress_bar = function(percent) {
$( "#progressbar" ).progressbar({
value: percent
});
};
})(jQuery);
#4
2
You can pass you session variables from your php script to JQUERY using JSON such as
您可以使用JSON将会话变量从php脚本传递给JQUERY
JS:
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe@jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
#5
1
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
您无法在JS中访问PHP会话变量/值,一个是服务器端(PHP),另一个是客户端(JS)。
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
您可以做的是将SESSION值传递给JS,例如,通过AJAX调用。在你的JS中,调用一个PHP脚本,它只是输出以返回给你的SESSION变量的值,然后使用你的JS来处理这个返回的信息。
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
或者将值存储在COOKIE中,可以通过任一框架访问它。虽然这可能不是您情况下的最佳方法。
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
或者你可以在PHP中生成一些返回/设置变量的JS,即:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
#6
0
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
严格来说,这并不是使用jQuery,但我发现这种方法比使用jQuery更容易。在这里可能有无穷无尽的方法来实现这个和许多聪明的方法,但并非所有方法都适用于我。但是,以下方法始终有效,我将其传递给万一以防万一。
Three javascript libraries are required, createCookie
, readCookie
and eraseCookie
. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
需要三个javascript库,createCookie,readCookie和eraseCookie。这些图书馆不是我的,但是大约5年前我开始使用它们并且不知道它们的起源。
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
要调用它们,您需要创建一个小PHP函数,通常作为支持库的一部分,如下所示:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
因此,要使用所有你现在必须包含在index.php文件中
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
现在在您的javascript library.js中,您可以使用以下代码恢复cookie:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
我希望这有帮助。
#7
0
Strangely importing directly from $_SESSION not working but have to do this to make it work :
奇怪地从$ _SESSION直接导入不起作用但必须这样做才能使其工作:
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
并在to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file