将多行PHP变量传递给Javascript函数

时间:2015-11-09 07:54:38

标签: javascript php character-encoding parameter-passing

我试图传递一个PHP变量,其中包含从SQL数据库读取的文本值(html内容)到Javascript函数。我尝试了所有不同的方法,例如json_encode(utf8_encode())preg_replace(),但它们似乎都没有效果。

这是我的代码:

<?php
$db = new PDO('mysql:host=localhost;dbname=ramtin_data;charset=utf8', 'root', '');

foreach($db->query('SELECT * FROM posts') as $row)
{
    $qtitle = $row['title'];
    $qcontent = $row['content'];
    $qpage = $row['page_id'];

    $qcontent = json_encode(utf8_encode($qcontent));

    echo "<script type='text/javascript'>
        displayPost('$qtitle', '$qcontent');
    </script>";
}
?>

我想提一下,当我在"字段中使用简单的一行(包括/content)在我的数据库中插入一行时,上面的代码就可以了。

我还尝试了以下代码并获得了相同的结果:

$qcontent = preg_replace('/\v+|\\\[rn]/','<br/>', $qcontent);

数据库中content字段内的值为以下字符串:

<img src="images/death_truck_titleDisplay.jpg" width="400" height="140" class="globalImageStyle" /><p class="postBodyContentParagraph">The work for another Construct2 game "<a href="http://ramt.in">Death Truck</a>" has been started.</p><p class="postBodyContentParagraph">I've had the idea since a few weeks ago and I'm amazed that how much it had developed into better shapes and more complex gameplay ideas only through the first weeks that I've started working on the graphics and the game codes/logic.</p><p class="postBodyContentParagraph">I'm actually done with the truck and pedestrian graphics and movement codes (plus the interaction code between pedestrians and the truck) and have included the game in the projects page as a Work In Progress. You can check some of the graphics and the idea of the whole game (plus some gameplay ideas) in the projects page.</p>

我应该如何将上述值传递给displayPost() Javascript函数?

更新

问题在于值内的单引号。接受的解决方案建议使用'替换\'所有$qcontent = str_replace("'", "\'", $qcontent);,这些json_encode()完美无缺。

然而"引用了结果,我发现删除包裹content.slice(1, content.length - 2)的最简单方法是使用content$qcontent是引用的第二个参数在Javascript函数内部的代码的PHP部分中的{{1}}。

1 个答案:

答案 0 :(得分:0)

因为你用单引号'包装你的输出,你需要逃避它们。

$qcontent = str_replace("'", "\'", $qcontent);