【问题标题】:Insert text format from an editable <div> or textarea into the database将可编辑 <div> 或 textarea 中的文本格式插入数据库
【发布时间】:2020-08-20 03:31:38
【问题描述】:

我目前正在为我自己的网站开发一个个人项目,我正在尝试添加将格式化文本存储到数据库中的功能。到目前为止,我所做的是能够将字体从斜体更改为粗体作为示例,但我完全不知道如何将其传递到数据库。

      <style>
            #fake_textarea {
      width: 100%;
      height: 200px;
      border: 1px solid red;
    }
    
    #jBold {
      font-weigth: bold;
    }
    #jItalic{
        font-style:italic;
    }
        </style>
        <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="jBold"><b>B</b></button><button id="jItalic"><i>I</i></button>
    <div id='fake_textarea' contenteditable>
      Select some text and click the button to make it bold...
      <br>Or write your own text
    </div>
        <script type="text/javascript">
            $(document).ready(function() {
      $('#jBold').click(function() {
        document.execCommand('bold');
      });
    });
     
        </script>
           <script type="text/javascript">
           $(document).ready(function() {
      $('#jItalic').click(function() {
        document.execCommand('italic');
      });
    });
     
        </script>
        
    </body>
    </html>

示例工作: codepen

【问题讨论】:

  • 您可以尝试使用:let content = $('#fake_textarea').html(); 获取 div 的内容。然后您可以使用 Ajax 将其发布到 PHP。
  • 感谢您为我指明正确的道路。我向它添加了新代码,现在我能够获取它的原始 html 值。 &lt;script type="text/javascript"&gt; $( "#htmls" ).click(function() { var htmlString = $( "#fake_textarea" ).html(); $( "#fake_textarea2" ).text( htmlString ); }); &lt;/script&gt;如何给你点赞?
  • 我已经发布了一个带有更多示例的答案。

标签: javascript php html css rich-text-editor


【解决方案1】:

要访问该可编辑 div 中的内容,您可以使用:

let content = $('#fake_textarea').html();

关于将数据发送到 PHP,最简单的解决方案可能是使用 Ajax

另类

如果您不想使用 Ajax 而是使用普通的表单发布,您可以让按钮触发一个函数,该函数获取内容并将其填充到表单中的隐藏字段中,然后提交。

类似这样的:(未经测试的伪代码)

HTML:

<form method="post" action="foo.php" id="some-form">
    <input type="hidden" name="content" id="some-hidden-input" />
    <div id="fake_textarea" ...></div>
    <button id="submit-button"></button>
</form>

JS:

$('#submit-button').on('click', function (e) {
    // Stop the default submission
    e.preventDefault();

    // Get the content from the div
    let content = $('#fake_textarea').html();

    // Store the content in a hidden input
    $('#some-hidden-input').val(content);

    // Submit the real form
    $('#some-form').submit();
});

注意

我在这些示例中使用 jQuery,因为您表明您正在使用它。所有这些当然也可以在 vanilla JS 中完成。

【讨论】:

  • 我添加的是这个,但它似乎不会向数据库发布任何内容。 &lt;script type="text/javascript"&gt; $(document).ready(function() { $( "#htmls" ).click(function() { var htmlString = $( "#fake_textarea" ).html(); $.ajax({ url: "postcontent.php", method: "POST", data: "pc=" + htmlString, success: function(response) { //handle response } }) }); }); &lt;/script&gt;
  • 仅使用上述代码很难帮助您,因为其中不包含调试信息。您可以尝试将数据作为对象传递,而不是手动构建数据字符串。将data: "pc=" + htmlString 更改为data: {pc: htmlString}
  • 我已经解决了,谢谢。我已经插入了一个答案以及 cmets 的最终编辑,因为我认为这将有助于其他人的项目。
【解决方案2】:

好的,所以我稍微调整了 Magnus 的代码,非常感谢他帮助我解决了这个问题。

textarea.php 在这里您将编写自己的内容、格式化文本并将其扔到您的 php 文件中,然后将其插入到数据库中。我也为那些想从中学习的人添加了 cmets。




    <style>
        #fake_textarea {
  width: 100%;
  height: 200px;
  border: 1px solid red;
}
<!-- Add css to modify the text -->
#jBold {
  font-weigth: bold;
}
#jItalic{
    font-style:italic;
}
#jUnderline{
    text-decoration: underline;
}
#jLT{
    text-decoration: line-through;
}
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<body>
    <!-- Put buttons here to modify the format -->
    <div>

    <select id="select_font" onchange="changeFont(this);">
  <option value="Arial">Arial</option>
  <option value="Sans Serif" selected>Sans Serif</option>
  <option value="Comic Sans MS">Comic Sans MS</option>
  <option value="Times New Roman">Times New Roman</option>
  <option value="Courier New">Courier New</option>
  <option value="Verdana">Verdana</option>
  <option value="Trebuchet MS">Trebuchet MS</option>
  <option value="Arial Black">Arial Black</option>
  <option value="Impact">Impact</option>
  <option value="Bookman">Bookman</option>
  <option value="Garamond">Garamond</option>
  <option value="Palatino">Palatino</option>
  <option value="Georgia">Georgia</option>
</select>
<select id="select-size" onchange="changeSize(this);">
<option value="4">4</option>
  <option value="8">8</option>
  <option value="12">12</option>
  <option value="16">16</option>
  <option value="20">20</option>
  <option value="24">24</option>
  <option value="28">28</option>
  <option value="32">32</option>
  <option value="36">36</option>
  <option value="40">40</option>
  <option value="44">44</option>
  <option value="48">48</option>
  <option value="52">52</option>
  <option value="56">56</option>
  <option value="58">58</option>
</select>
<button id="jBold"><b>B</b></button><button id="jItalic"><i>I</i></button><button id="jUnderline">U</button><button id="jSuperScript">A<sup>A</sup></button><button id="jSubScript">A<sub>A</sub></button>
<button id="jLT">A</button>
<div>
    <!-- Add a form -->
    <form method="post" action="postcontent.php"  id="contentform">
    <!-- Add some hidden input in order for the form to submit some sort of value -->
        <input type="hidden" name="content" id="hiddeninput" />
        <!-- Add a place to insert the content -->
        <div id='fake_textarea' contenteditable>
              Select some text and click the button to make it bold...
              <br>Or write your own text
        </div>
        <!-- Add a submit button-->
        <button id="submit">Submit</button>
    </form>
    <!-- Script to make a selected text bold-->
        <script type="text/javascript">
            $(document).ready(function() {
                $('#jBold').click(function() {
                    document.execCommand('bold');
                });
            });

        </script>
        <!-- Script to make a selected text italic-->
           <script type="text/javascript">
           $(document).ready(function() {
                $('#jItalic').click(function() {
                    document.execCommand('italic');
                });
            });

        </script>
        <!-- Script to make add an underline-->
           <script type="text/javascript">
           $(document).ready(function() {
                $('#jUnderline').click(function() {
                    document.execCommand('underline');
                });
            });

        </script>
        <!-- Script to make make selected text a superscript-->
           <script type="text/javascript">
           $(document).ready(function() {
                $('#jSuperScript').click(function() {
                    document.execCommand('superscript');
                });
            });

        </script>
        <!-- Script to make make selected text a subscript-->
           <script type="text/javascript">
           $(document).ready(function() {
                $('#jSubScript').click(function() {
                    document.execCommand('subscript');
                });
            });

        </script>
                <!-- Script to add a line-through-->
           <script type="text/javascript">
           $(document).ready(function() {
                $('#jLT').click(function() {
                    document.execCommand('strikeThrough');
                });
            });

        </script>




        <!-- Changes the font type -->
        <script  type="text/javascript">
        function changeFont(font) {
            var sel = window.getSelection(); // Gets selection
            if (sel.rangeCount) {
            // Creates a new element, and insert the selected text with the chosen font inside
            var e = document.createElement('span');
            e.style = 'font-family:' + font.value + ';'; 
            e.innerHTML = sel.toString();

            // https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
            var range = sel.getRangeAt(0);
            range.deleteContents(); // Deletes selected text…
            range.insertNode(e); // … and inserts the new element at its place
            }
        }
        </script>
        <!-- Changes the font size -->
        <script  type="text/javascript">
        function changeSize(size) {
        var sel = window.getSelection(); // Gets selection
            if (sel.rangeCount) {
            // Creates a new element, and insert the selected text with the chosen font inside
            var e = document.createElement('span');
            e.style = 'font-size:' + size.value + 'px;'; 
            e.innerHTML = sel.toString();

            // https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
            var range = sel.getRangeAt(0);
            range.deleteContents(); // Deletes selected text…
            range.insertNode(e); // … and inserts the new element at its place
            }   
        }

        </script>

        <!-- Script to add value to the hidden input then submits it-->
        <script  type="text/javascript">

        $( "#submit" ).click(function() {

            var htmlString = $( "#fake_textarea" ).html();
            $('#hiddeninput').val(htmlString);
            // Submit the real form
            $('#contentform').submit();
        });

        </script>
</body>


postcontent.php 该文件会将隐藏输入抛出的值提交到数据库。

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

//grabs the name of the hidden input that was posted
    $pcd= $_POST['content'];
    $uid="";
    $bid="";
    $cnum="";
    $cid="";
    //connect to database
    $mysqli = new mysqli("localhost","root","","nw");
//error checking the connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}
//submits it
$stmt= $mysqli->prepare("INSERT INTO usercontent (userid, bookid, chapterid, chapternum,data) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $uid, $bid,$cid, $cnum,$pcd);
$stmt->execute();



$stmt -> close();
$mysqli -> close();
}


?>

希望这对某人的帮助与此人对我的帮助一样多。

【讨论】:

  • 警告!你对SQL injection攻击敞开大门!您应该使用参数化的prepared statements,而不是像这样直接在查询中使用完全未转义的用户数据。 永远永远永远相信用户输入。
  • 我只是将其设置为示例,但这里是参数化语句。
猜你喜欢
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
相关资源
最近更新 更多