首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我的文本编辑器生成了额外的大括号,如何摆脱它?

我的文本编辑器生成了额外的大括号,如何摆脱它?
EN

Stack Overflow用户
提问于 2018-06-15 22:33:30
回答 1查看 227关注 0票数 0

我需要设置一个文本编辑器,以便在我的项目(Django 2.0)中有更好的发布功能,为此我使用了quilljs。这是工作,但一些错误是附加与帖子。

代码在这里

 <form action="" method="post">
      {% csrf_token %}  
      <input name="description" type="hidden">
      <div id="editor-container">
      </div>

      <input class="ui button" type="submit" value="Post" />
    </form>

Javascript

var quill = new Quill("#editor-container", {
    modules: {
        toolbar: [
            ['bold', 'italic'],
            ['link', 'blockquote', 'code-block', 'image'],
            [{
                list: 'ordered'
            }, {
                list: 'bullet'
            }]
        ]
    },
    placeholder: 'Compose an epic...',
    theme: 'snow'
});
var form = document.querySelector('form');
form.onsubmit = function() {
    // Populate hidden form on submit
    var about = document.querySelector('input[name=description]');
    about.value = JSON.stringify(quill.getContents());

    console.log("Submitted", $(form).serialize(), $(form).serializeArray());

};

post后,结果是这样的

{“ops”:{“insert”:“具有感知能力的机器人,并且是地球上唯一仍在运行的机器人。\n”}}

如何去掉这些多余的花括号。提亚

EN

回答 1

Stack Overflow用户

发布于 2018-06-17 04:52:22

首先,你得到的结果

{“ops”:{“insert”:“具有感知能力的机器人,并且是地球上唯一仍在运行的机器人。\n”}}

不是一个错误。Quill的getContents()函数在编辑器中返回JSON格式的文本(这就是为什么有那些大括号的原因)。此外,您还对该JSON进行了字符串化,以获得该字符串。

看看这个来自奎尔的游乐场页面,以理解返回的数据格式:link

如果您只想删除这些大括号并获取输入文本,则可以在客户端的onsubmit方法中获取文本,也可以在接收表单数据的django视图的服务器端获取文本。

1. JS中的客户端:

form.onsubmit = function() {
    // Populate hidden form on submit
    var about = document.querySelector('input[name=description]');
    //get JSON from quill editor
    var jsonData = quill.getContents();
    //access "insert" data from the JSON
    about.value = jsonData.ops[0].insert;

    console.log("Submitted", $(form).serialize(), $(form).serializeArray());
};

Python2.中的服务器端:

import json

...
#get JSON String from the request and parse it to python JSON dictionary
jsonData = json.loads(req.body.description)
#access "insert" data from the JSON
inputText = jsonData["ops"][0]["insert"]
...

注意:这只用于从获取纯文本数据(如果存在)。您也可以从JSON访问其他格式化的文本。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50877685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档