我尝试编写一些社交网络代码。所以我有一个带有textarea的表格来撰写和发送帖子。现在,如果我想写例如:
您好,这是第一行
这是第二行
它完全像这样存储在我的数据库中。现在,如果我要输出帖子,则查询数据库并形成JSON字符串。问题是新行也位于JSON字符串中,因此我当然会收到此错误: JSON.parse:字符串中的控制字符错误
我尝试使用nl2br()进行某些操作,但没有任何帮助。
这是与数据库中的帖子数据一起形成json字符串的代码
$response = "[";
foreach($followingposts as $post) {
$response .= "{";
$response .= '"PostId": '.$post['id'].',';
$response .= '"PostBody": "'.$post['body'].'",';
$response .= '"PostedBy": "'.$post['username'].'",';
$response .= '"PostDate": "'.$post['posted_at'].'",';
$response .= '"Likes": "'.$post['likes'].'"';
$response .= "},";
}
$response = substr($response, 0, strlen($response)-1);
$response .= "]";
http_response_code(200);
echo $response;
这是Ajax请求,用于在timelin上显示帖子
$.ajax({
type: "GET",
url: "api/profileposts?username=<?php echo $profileusername;?>",
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var posts = JSON.parse(r)
$.each(posts, function(index) {
$('.timelineposts').html(
$('.timelineposts').html() + '<blockquote class="blockquote" style="margin-left:45px;max-width:650px;width:auto;margin-bottom:40px;"><p class="mb-0" style="color:rgb(255,255,255);">'+posts[index].PostBody+'</p><footer class="blockquote-footer" style="color:rgb(137,137,137);font-weight:500;">von '+posts[index].PostedBy+'<button data-id="'+posts[index].PostId+'" class="btn btn-primary" type="button" style="background-color:rgb(30,40,51);padding-right:0px;padding-left:0px;padding-top:0px;padding-bottom:0px;margin-left:15px;border:none;"><i class="fa fa-heart" style="font-size:27px;color:rgb(255,0,0);"></i><span style="color:rgb(255,0,0);margin-left:15px;">'+posts[index].Likes+' Likes</span></button></footer></blockquote>'
)
$('[data-id]').click(function() {
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "api/likes?id=" + $(this).attr('data-id'),
processData: false,
contentType: "application/JSON",
data: '',
success: function(r) {
var res = JSON.parse(r)
$("[data-id='"+buttonid+"']").html('<i class="fa fa-heart" style="font-size:27px;color:rgb(255,0,0);"></i><span style="color:rgb(255,0,0);margin-left:15px;">'+res.Likes+' Likes</span>')
console.log(r)
},
error: function(r) {
console.log(r)
}
});
})
})
},
error: function(r) {
console.log(r)
}
});
答案 0 :(得分:1)
如果使用别名查询列名,那么很简单:
SELECT id AS PostId,
body AS PostBody,
username AS PostedBy,
posted_at AS PostDate,
likes AS Likes
FROM table_name ....
然后像以前一样将行提取到$followingposts
中并输出JSON:
echo json_encode($followingposts);
就是这样。
如果这是您实际上并未构造查询的CMS或应用程序,则:
foreach($followingposts as $post) {
$response[] = array(
'PostId' => $post['id'],
'PostBody' => $post['body'],
'PostedBy' => $post['username'],
'PostDate' => $post['posted_at'],
'Likes' => $post['likes']);
}
echo json_encode($response);