不能在JavaScript中使用我的php变量

时间:2014-09-12 12:13:23

标签: javascript php

我有一个php变量。然后在按钮上点击JS,我必须打开一个包含该变量的链接。根据其他主题,这必须起作用,但事实并非如此。如果点击它就没有任何反应。

<?php
    $id = 'string';
?>
<SCRIPT language="JavaScript">
   function openBox() {
       php_var = <?php echo $id; ?>;
       targetURL = "other_page.php?id=" + php_var
       theBox = window.open(targetURL, 'theResults', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=1, width=600,height=680,left=10,top=10');
   }
</SCRIPT>

*修改: 好的,我忘记了var';。 修改后的代码(如下所示)现在打开所需的站点,但var为空。如果我只是在php中回应它,它就具有它的价值。

<?php
    $id = 'string';
?>
<SCRIPT language="JavaScript">
   function openBox() {
       php_var = '<?php echo $id; ?>';
       targetURL = "other_page.php?id=" + php_var
       theBox = window.open(targetURL, 'theResults', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=1, width=600,height=680,left=10,top=10');
   }
</SCRIPT>

4 个答案:

答案 0 :(得分:5)

您需要添加引号和var

var php_var = '<?php echo $id; ?>';
var targetURL = "other_page.php?id=" + php_var
var theBox = window.open(targetURL, 'theResults', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=1, width=600,height=680,left=10,top=10');

答案 1 :(得分:1)

代表OP 发表。

解决方案:我有html扩展而不是php,因此PHP代码没有被执行。

答案 2 :(得分:0)

如何更改线

php_var = <?php echo $id; ?>;

php_var = '<?php echo $id; ?>';

你是否绝对确定你的PHP脚本中定义了$ id并且它没有空字符串值?

答案 3 :(得分:0)

对字符串使用引号,否则脚本认为您将名为 string 的变量分配给 php_var

php_var = "<?php echo $id; ?>";

另外,你错过了这一行末尾的一个专栏:

targetURL = "other_page.php?id=" + php_var;