2015-11-09 07:54
浏览 52


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:

$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');

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="">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?


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);
    解决 无用
    打赏 举报

相关推荐 更多相似问题