我尝试编写一个小型社交网络。所以我有一个带有文本区域的表单来编写和发送帖子。现在如果我想写例如:
你好,这是第一行
这是第二行
它在我的数据库中的存储方式与此完全相同。现在,如果我想输出帖子,我会查询数据库并形成一个 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 请求
$.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)
}
});
最佳答案
如果您使用列名的别名进行查询,则很简单:
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);
关于javascript - 我从 textarea 输入得到了 json 中的多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700090/