简体   繁体   English

语法错误:丢失; JavaScript中的before语句

[英]SyntaxError: missing ; before statement in Javascript

This is the code concerned: 这是有关的代码:

    var membre = '<?= $_SESSION['login'] ?>';

I get this error when I check the Firebug console: SyntaxError: missing ; 当我检查Firebug控制台时出现此错误:SyntaxError:missing; before statement in Javascript JavaScript中的before语句

And the Javascript doesn't execute itself. 而且Javascript本身不会执行。 What's weird is that this used to work, and it also works in local, without an issue. 奇怪的是,它曾经可以工作,并且也可以在本地工作,没有问题。

Do you know why? 你知道为什么吗? Or is there another way to get the 'login' SESSION in a Javascript variable? 还是有另一种方法来获取Javascript变量中的“登录”会话?

Thanks 谢谢

You should not dump PHP variables into JavaScript strings like that. 您不应该那样将PHP变量转储到JavaScript字符串中。 There is a mechanism already in place: 已经存在一种机制:

var membre = <?php echo json_encode($_SESSION['login']) ?>;

This will automatically add quotes and escape any problematic characters in a string. 这将自动添加引号并转义字符串中任何有问题的字符。 It can also be used for numbers and booleans (passed raw), and even arrays (converted to literals). 它也可以用于数字和布尔值(通过原始值),甚至用于数组(转换为文字)。

Your line of code should be either this (1): 您的代码行应为以下(1):

// double quotes on the outside and single quotes on the inside or vice versa
var membre = "<?= $_SESSION['login'] ?>";

or this (2): 或此(2):

var membre = '<?= $_SESSION[' + login + '] ?>';

This depends on if you want to access a property with the name "login" (1) or if you want to access a property with the content of a javascript variable named "login" (2). 这取决于您是否要访问名称为“ login”的属性(1)还是要访问名为“ login”的javascript变量的内容的属性(2)。

Anyway, your code ( var membre = '<?= $_SESSION['login'] ?>'; ) is actually two separated string with the name "login" in the middle. 无论如何,您的代码( var membre = '<?= $_SESSION['login'] ?>'; )实际上是两个分开的字符串,中间名为“ login”。 So javascript wants to assign the string "<?= $_SESSION[" to the variable membre and expects a semicolon after that. 因此,javascript希望将字符串"<?= $_SESSION["分配给变量membre并期望在此后使用分号。 But instead of a semicolon it finds the word "login", which it thinks is a different statement. 但是,它找到的不是一个分号,而是找到了“登录”一词,它认为这是另一种说法。 That is why you get the error "missing ; before statement". 这就是为什么会出现错误“ missing; before statement”的原因。

EDIT 编辑

As Felix Kling pointed out, I was an the wrong path here, since the PHP code inside <?= ... ?> is evaluated first (see his comment below). 正如Felix Kling指出的那样,这里是错误的路径,因为首先对<?= ... ?>的PHP代码进行了评估(请参阅下面的评论)。 So, the inner single quotes are not the issue here. 因此,内部单引号在这里不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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