简体   繁体   中英

how to get session value to client-side without echo it out

I want to use the session['something'] value inside my js, what if I don't print it out somewhere, how could I use that value?

only 2 ways I found 1) use hidden field trick 2) ajax

note : I've a 'huge' session data because it's an array

update : I already have the session set in my index.php, and I want to use the array (the session) in my js file.

客户端无法直接访问任何$_SESSION变量,因此,如果您不能或不想在JS中回显变量的内容,则只有两个选项可用。

Put it directly into JavaScript. A JSON "string" is perfectly parseable JavaScript, which is why one could eval(jsonStr); and get the same thing as JSON.parse(jsonStr) (although eval is discouraged for security reasons). If your nested _SESSION data is safe (eg sanitized already for JS), then there is nothing wrong with the following:

<script type="text/javascript">
var session = <?php echo json_encode($_SESSION); ?>;
</script>

... then later on ...

<script type="text/javascript">
$(document).ready(function() {
    doSomething(session);
}
</script>

You may wish to NOT dump the entire session to the client, in which case, just rebuild what you want (also showing an example of CDATA here since it is in a XHTML tree, if you're conscious of that):

<?php
$jsOut['username'] = $_SESSION['username'];
$jsOut['public'] = $_SESSION['public'];
// omit $_SESSION['passhash']
$encodedJSON = json_encode($jsOut);
?>
<script type="text/javascript">
//<![CDATA[
var session = <?php echo $encodedJSON; ?>;
//]]>
</script>

You can put a <script> tag right in the body/head of your HTML (ie as CDATA). It can be as simple as declaring an object in global or namespaced scope. Then just access that object (by whatever name you declared it with var as) within, by passing it into some "init" function which can be in any JS file included/loaded in the page (ie external or inline).

Remember, PHP is simply a preparser (hence the name) to whatever it is you want to generate. In this case, you're generating client-side code which can consist of HTML, CSS, even JS, or any other client-side tech (eg VBScript for IE). Heck, PHP can even dynamically write JavaScript if you wanted, which in its most simple form is what this solution is recommending.

If you need session data in the your presentation layer for continuous access, then you have two methods and you already have mentioned them.

  1. Dump all the data in a JavaScript array and then use it.
  2. Use AJAX and fetch it from your server.

If you are using a MVC framework, you can write a separate controller which gives you different methods for accessing the SESSION data. This way you will not expose the data all at once and can write orgazined code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM