dousao6260 2015-11-09 07:54 采纳率: 0%
浏览 52
已采纳

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

I'm trying to pass a PHP variable holding a text value (html content) read from SQL database to a Javascript function. I'm trying all different approaches such as json_encode(utf8_encode()) and preg_replace() but none of them seem to work.

Here's my code:

<?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>";
}
?>

Just want to mention that when I insert a row in my database with a simple line (including "and /) in the content field, the above code works.

I've also tried the following code and got the same result:

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

The value inside the content field in the database is the following string:

<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>

How should I pass the above value to the displayPost() Javascript function?

UPDATE


The problem was with the single quotes inside the value. The accepted solution suggested all 's to be replaced with \' using $qcontent = str_replace("'", "\'", $qcontent); which worked perfectly.

The result however was quoted by json_encode() which I found the easiest way to remove the wrapping "s to be using content.slice(1, content.length - 2) (content is the second parameter which refers to $qcontent in the PHP section of the code) inside of the Javascript function.

  • 写回答

1条回答 默认 最新

  • duanqian9593 2015-11-09 08:21
    关注

    Because you wrap your output in single quotes ' you need to escape those.

    $qcontent = str_replace("'", "\'", $qcontent);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?