0

I am trying to pass a PHP Session variable into a js function but failing.

Here's what I'm trying. The desired end result is that it reads the correct JSON file based on user logged in details.

Is this even possible?

var username = <?=$_SESSION[username]?>;
$('#aboutContent').redactor({ 
    imageGetJson: '/users/'+username+'/gallery/gallery.json'
    }); 
}

I've also tried:

imageGetJson: '/users/<?=$_SESSION[username]?>/gallery/gallery.json'

But still no dice.

UPDATE - FIXED

The problem was that this js was in an external file, not in the same file where the session_start is called - so i moved it into the file as opposed to extrenal and all is good now. Using this and works perfectly (don't need to set var username):

imageGetJson: '/users/<?=$_SESSION['username']?>/gallery/gallery.json'
4

3 回答 3

2

Lets say the username is John. The line

var username = <?=$_SESSION[username]?>;

would be echoed to client like this:

var username = John;

which obviously is not valid Javascript. Try enclosing the username string in quotes:

var username = '<?=$_SESSION[username]?>';
于 2013-05-02T06:03:39.107 回答
1

That is practically not possible. You can't bring in the server side concepts to client-side.

于 2013-05-02T06:02:19.000 回答
0

You're not properly quoting the variable. json_encode() will take care of this, as well as encoding things properly.

<?php session_start(); ?>
var username = <?= json_encode($_SESSION['username']) ?>;
于 2013-05-02T06:02:10.080 回答