Javascript 如何从 .js 文件中的 jQuery 函数访问 PHP 会话变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4365738/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:06:41  来源:igfitidea点击:

How to access PHP session variables from jQuery function in a .js file?

phpjavascriptjquery

提问by Ahmad Farid

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
   });
});

回答by Erik

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 从服务器端脚本返回。

回答by Krimo

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'])回显到您选择的任何元素: <p id="sessionOrigin"><?=$_SESSION['origin'];?></p>

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

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>

<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>

回答by icc97

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);

回答by Mark

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['[email protected]'];

$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 

回答by SW4

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 passor returnthe 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,然后使用您的 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>";
?>

回答by Alexander

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, readCookieand eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

需要三个 javascript 库createCookiereadCookieeraseCookie。这些库不是我的,但我大约 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.

我希望这有帮助。

回答by Ardhi

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