2014-05-13 110 views
0

我想在以下方式在JavaScript中使用php变量,但它不工作。 任何人都可以让我知道什么是错在下面的代码里面的PHP PHP变量

include './connection.php'; 
$rating[]=$_GET['rating']; 

echo '<script>'; 
echo 'document.getElementById(' .$rating. ').checked = true;'; 
echo '</script>'; 
+0

如果您启用错误报告,您应该会收到一条消息,告诉您发生了什么。与检查呈现的html时相同 – PeeHaa

+0

从第二行的$ rating中删除括号。 – WillardSolutions

+0

尝试做'echo'document.getElementById(''。$ rating。'“).checked = true;';' – PEIN

回答

2

我猜测它应该是一个字符串,如果因此你要引用它

include './connection.php'; 
$rating = $_GET['rating']; 

echo '<script>'; 
echo 'document.getElementById("' .$rating. '").checked = true;'; 
echo '</script>'; //   ^^   ^^ 
3

您正在尝试一种呼应数组,而不是数组中的值。

为什么将$rating定义为数组?只需执行以下操作:

include './connection.php'; 
$rating=$_GET['rating']; 
?> 
<script> 
document.getElementById('<?php echo $rating; ?>').checked = true; 
</script> 
<?php 
// continue script 

您还需要考虑解决当前存在的跨站点脚本(XSS)漏洞。

+0

如果我们正在优化,为什么还要设置'$ rating'呢?只要做'<?= $ _ GET ['rating']?>'。 – Wogan

+0

@Wogan是的。人们可以这样做,但真正的'$ rating'应该在回复出去之前进行消毒。 –

+0

@Wogan和Mike:非常感谢。我知道了 – user3541562

0
include './connection.php'; 
    $rating = $_GET['rating']; // forget the square brackets, you don't need an array made here 

    echo '<script>'; 
    echo 'document.getElementById("' . htmlspecialchars($rating) . '").checked = true;'; 
    echo '</script>'; 

htmlspecialchars确保你没有将你的网站容易受到Cross-site scripting。 document.getElementById接受一个字符串参数,所以你需要用引号包装它。

+0

应该可能链接到英文wikipedia; – ccKep

+0

@ccKep糟糕。修正了这一点,谢谢。 – Khub