我正在使用PDO来执行查询。我有这个问题:我有一个来自女巫的<textarea>
元素我正在获取文本并将其发布到服务器端并在我准备PDO准备后将其添加到数据库中:
$insertQuery = $db->prepare("INSERT INTO feedback (userName, comment, time_stamp, languageCode, userIp) VALUES (:usernaem, :comment, '". $now ."', :lang, '". $ip ."')");
$insertQuery->bindValue(':comment',nl2br($_POST['comment']));
...
在我网络的其他地方,我从数据库中获取此“评论”并将其提取到json字符串:
try {
$commentQuery = $db->query("SELECT userName, time_stamp, comment, languageCode FROM feedback LIMIT 10");
} catch (PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => $ex->getMessage())));
}
$result = $commentQuery->fetchAll(PDO::FETCH_ASSOC);}
$commentsJson = json_encode($result);
$commentsJson
我正在插入一些javascript var:
var comments = JSON.parse('<?php echo $commentsJson; ?>');
这里我的chrome浏览器抛出异常。
如果我在<textarea>
中有此文字:
我把它提交给db:
这是一些评论
这是新的评论线
在db中保存为:
This is some comment<br />
and this is new line of comment
但是当我从数据库中获取它时,我得到了这个:
var comments = JSON.parse('[{"userName":"Test","time_stamp":"2013-04-04 10:17:43","comment":"This is some comment<br \/>\nand this is new line of comment", ...
之后我的浏览器异常说:
“Uncaught SyntaxError:Unexpected token”
任何帮助将不胜感激!
答案 0 :(得分:-1)
<?php
$result = $commentQuery->fetchAll(PDO::FETCH_ASSOC);
$commentsJson = json_encode($result);
?>
...
function replacetext(text, what, to){
var searchfor = what.replace(/\r/gi,'').replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var replacewith = to.replace(/\r/gi,'');
var flags = 'gi';
var searchexp = new RegExp(searchfor,flags);
text = text.replace(searchexp,replacewith);
return text;
}
var tmp = '<?php echo $commentsJson; ?>';
tmp = replacetext(tmp, "\n", '<br>');
感谢您的帮助!