如何获得CodeMirror文本编辑器的值
时间:2020-02-23 14:45:52 来源:igfitidea点击:
在本教程中,我们将学习获得CodeMirror编辑器中的值。
下载
CodeMirror:http://codemirror.net/
jQuery的:https://jquery.com/
可选的:
SublimeText:https://www.sublimetext.com/
原子:https://atom.io/
Brackets:http://brackets.io/
eclipse:https://eclipse.org/
适用于Windows的XAMPP:https://www.apachefriends.org/download.html
适用于Mac的MAMP:https://www.mamp.info/en/
步骤
在codemirror项目文件夹中创建form.php。
在form.php文件中包括必要的文件。
<!DOCTYPE html> <html> <head> <title>CodeMirror</title> <link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css"> </head> <body> <!-- javascript --> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script> <script type="text/javascript" src="js/default.js"></script> </body> </html>
建立表单
<form id="preview-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <textarea class="codemirror-textarea" name="preview-form-comment" id="preview-form-comment"><?php echo $comment; ?></textarea> <br> <input type="submit" name="preview-form-submit" id="preview-form-submit" value="Submit"> </form>
现在我们需要编写一些php代码来处理提交的表单数据。
<?php //initially $comment = null; //if the form is submitted if($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['preview-form-comment'])) { $comment = $_POST['preview-form-comment']; } ?>
至此,我们的form.php文件将包含以下代码。
<?php //initially $comment = null; //if the form is submitted if($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['preview-form-comment'])) { $comment = $_POST['preview-form-comment']; } ?> <!DOCTYPE html> <html> <head> <title>CodeMirror - Form</title> <link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css"> </head> <body> <form id="preview-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <textarea class="codemirror-textarea" name="preview-form-comment" id="preview-form-comment"><?php echo $comment; ?></textarea> <br> <input type="submit" name="preview-form-submit" id="preview-form-submit" value="Submit"> </form> <div id="preview-comment"><?php echo $comment; ?></div> <!-- javascript --> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script> <script type="text/javascript" src="js/default.js"></script> </body> </html> </pre></code> <p>To get the value of the CodeMirror text editor we need to write some javascript code in the default.js file. </p> <pre><code> $(document).ready(function(){ //code here... var code = $(".codemirror-textarea")[0]; var editor = CodeMirror.fromTextArea(code, { lineNumbers : true }); //when form submitted $("#preview-form").submit(function(e){ var value = editor.getValue(); if(value.length == 0) { alert("Missing comment!"); } }); });
因此,在上面的javascript代码中,我们正在检查是否提交了"预览表单"表单,然后使用getValue()函数获取CodeMirror文本编辑器的值。
然后我们检查用户是否在编辑器中输入了任何文本。