我在文本区域输入的 json 中有一个多行字符串

Posted

技术标签:

【中文标题】我在文本区域输入的 json 中有一个多行字符串【英文标题】:I've got a multiline string in json from textarea input 【发布时间】:2019-02-14 22:31:13 【问题描述】:

我尝试编写一个小型社交网络。所以我有一个带有 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 请求


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


【问题讨论】:

为什么不使用 php 的内置 JSON 工具将您的对象编码为 JSON? 补充一下,内置的json_encodejson_decode 函数会避开这些东西。它做得很好(非UTF-8除外)。此外,当您显示文本时,您可以简单地使用 css white-space:pre 样式,您不必为转换任何内容而烦恼。这带来了它自己的问题,例如,如果你有所有这些 &lt;br&gt; 标记,则在输出中使用 htmlentities,或者将修改后的数据放回文本区域进行编辑。 我在上面暗示的最后一件事,如果您将用户输入的内容存储在数据库中,您需要在输出给“其他”用户之前转义此内容(使用 'htmlentities' )。如果您不这样做,您可以允许 1 个用户将 javascript 代码输入到您的数据库中,然后显示给其他用户 - 这是......不好。 【参考方案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);

【讨论】:

以上是关于我在文本区域输入的 json 中有一个多行字符串的主要内容,如果未能解决你的问题,请参考以下文章

禁止在文本区域输入某些字符

在发布和重用值后,在文本区域中显示用换行符分隔的值

在文本区域输入键

如何使在文本区域中输入的文本对应于特定的单选按钮?

如何在文本区域中显示数组内容?

在 JS/JQuery 中按 ENTER 键之前,如何仅捕获您在文本区域中输入的行? [复制]