Я пытаюсь передать переменную PHP, содержащую текстовое значение (содержимое html), считываемое из базы данных SQL, в функцию 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
в разделе PHP кода) внутри функции Javascript.
Поскольку вы завершаете вывод в одинарных кавычках '
вам нужно их избежать.
$qcontent = str_replace("'", "\'", $qcontent);
json_encode()
не избежать одиночных кавычек '
?