1

I'm getting this error in Firebug :

SyntaxError: unterminated string literal

Panel_Measurements[i] = "<br />

And now all off my functions fail to work... I've tried multiple solutions, but none of them work... this is my code :

<script type="text/javascript" language="javascript>
   <?php
      $i = 0;
      while(isset($dbPanel_Name[$i]))
      {
   ?>

          Panel_brand_type[i]   = "<?php echo addslashes($dbPanel_Brand_Type[$i]); ?>";
          Panel_description[i]  = "<?php echo addslashes($dbPanel_Description[$i]); ?>";
          Panel_measurements[i] = "<?php echo addslashes($dbPanel_Measurements[$i]); ?>";
          Panel_warranty[i] = "<?php echo addslashes($dbPanel_Warranty[$i]); ?>";
          i++;
   <?php
         $i++;
       }
    ?>
</script>

If there's any other way to get PHP variables into Javascript, I would love to know! Any type of help is usefull to me.

Sincerly,

Harmen Brinkman

4

1 回答 1

6

在 JavaScript 中注入字符串文字(以及几乎所有其他类型的值)的更好方法是json_encode

Panel_brand_type[i] = <?php echo json_encode($dbPanel_Brand_Type[$i]); ?>;

请注意,我删除了 PHP 标记周围的双引号,json_encode它们自己提供。

此解决方案的唯一潜在问题是您注入的字符串必须是 UTF-8,但您现有的代码addslashes也有类似的问题(它盲目地假设您使用的是单字节编码)所以恕我直言,没有回归.

最后,请确保在尝试访问 PHP 变量之前实际设置了它们!如果没有这样的变量,PHP 会在需要 JavaScript 代码的地方发出警告:这肯定会毁了你的一天。

于 2013-03-07T10:04:53.647 回答