通过在PHP中回显将字符串传递到javascript函数

时间:2014-12-09 22:40:14

标签: javascript php html

在PHP文件中,以下代码创建一个HTML表,并使用mysql数据库表中的数据填充它。

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
<h1>

    <script>
        function doThis(input) {
            document.write(input);
        }
    </script>

    <?php
    $sql = "select * from performance where title='cats';";
    $handle = $conn->prepare($sql);
    $handle->execute();
    $res = $handle->fetchAll();

    foreach ($res as $row) {
        echo "<tr onmouseover=\"ChangeColor(this, true);\"
          onmouseout=\"ChangeColor(this, false);\" 
          onclick=\"doThis(\"$row[0]\");\">";
        echo "<td>$row[0]</td>";
        echo "</tr>";
    }
    ?>
</h1>
</body>
</html>

我遇到的问题是回显doThis(\&#34; $ row [0] \&#34;)虽然传递了一个整数,但不打印行[0]数据。 doThis(22)确实打印22.我认为问题在于引号和转义字符,但我无法使其正常工作。

我在这里使用document.write()方法作为测试 - 在有人告诉我我不应该使用它之前!

我是一名网页设计初学者,所以我欢迎任何有关在javascript函数中更好地使用我的表格数据的建议。

1 个答案:

答案 0 :(得分:2)

试试这个,如果没有其他你不需要所有那些可能会让你和PHP混淆的转义字符。

echo '<tr onmouseover="ChangeColor(this, true);" ' .
     'onmouseout="ChangeColor(this, false);" ' .
     'onclick="doThis(' . sprintf("'%s'",$row[0]) . ');">';