繁体   English   中英

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

[英]Passing Multi-line PHP variable to Javascript function

我正在尝试将包含从SQL数据库读取的文本值(html内容)的PHP变量传递给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函数?

UPDATE


问题在于值内的单引号。 接受的解决方案建议使用$qcontent = str_replace("'", "\\'", $qcontent);将所有'替换为\\' $qcontent = str_replace("'", "\\'", $qcontent); 效果很好。

结果却是由援引json_encode()我发现,除去包装的最简单的方法" s到使用content.slice(1, content.length - 2) content是指第二个参数$qcontent在PHP代码部分)。

因为你裹在单引号的输出'你需要逃生者。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM