2014-05-13 113 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