CKEditor 4 setData失效求助:无法回显历史描述内容
CKEditor 4 编辑时无法回显描述文本的问题
我使用CKEditor 4从表单获取文本,展示数据环节正常,但编辑已插入内容时遇到问题:无法让CKEditor回显之前从编辑器获取的描述文本用于二次编辑。
编辑页面初始代码(可正常显示标题)
<head> <script src="https://cdn.ckeditor.com/4.20.2/standard/ckeditor.js"></script> </head> <form action="/rel/<%=project.id%>/<%=releasenote.id%>?_method=PUT" method="POST" > <!-- Title input--> <div class="form-floating mb-3"> <input class="form-control" id="title" name="title" type="text" required /> <label for="text">Title</label> </div> <!-- Description input--> <div class="mb-3"> <textarea class="form-control h-25" id="description" name="description"></textarea> <label for="text"></label> </div> <script> CKEDITOR.replace('description').setData("<%=releasenote.title%>"); // 此代码可正常在编辑器中显示标题 </script>
尝试回显描述的代码(编辑器消失且无法显示内容)
<script> CKEDITOR.replace('description').setData("<%=releasenote.description%>"); // 此代码无效,编辑器直接消失 </script>
后端路由代码
router.put('/rel/:p_id/:r_id', async (req, res) => { //console.log(req.body) const project = await Project.findById(req.params.p_id) let releasenote try { releasenote = await ReleaseNote.findById(req.params.r_id) releasenote.user = await req.user.id, releasenote.project = project.id, releasenote.title = req.body.title, releasenote.description = req.body.description, await releasenote.save() res.redirect(`/rel/${project.id}/${releasenote.id}`) } catch { if (releasenote == null){ res.redirect(`/rel/${project.id}/${releasenote.id}`) } else { res.render('releasenotes/edit', { project: project, releasenote: releasenote, error: 'Error Updating Releasenote' }) } } })
解决方案
1. 处理富文本的特殊字符转义
releasenote.description是富文本内容,包含HTML标签、引号等特殊字符,直接用"<%=releasenote.description%>"会破坏JS字符串的语法结构,导致脚本出错,编辑器加载失败。
改用JSON.stringify处理内容,生成合法的JS字符串:
<script> CKEDITOR.replace('description').setData(<%= JSON.stringify(releasenote.description) %>); </script>
JSON.stringify会自动转义所有特殊字符(如双引号、换行、HTML标签),确保内容能正确传入setData方法。
2. 确保编辑器初始化完成后再设置数据
CKEditor的初始化是异步过程,直接链式调用setData可能在编辑器未就绪时执行,导致失败。改用instanceReady事件确保编辑器加载完成后再设置数据:
<script> CKEDITOR.replace('description', { on: { instanceReady: function() { this.setData(<%= JSON.stringify(releasenote.description) %>); } } }); </script>
3. 验证数据完整性
- 在编辑页面模板中临时添加
<p><%- releasenote.description %></p>,确认releasenote.description确实存在且内容正确。 - 检查后端路由中
req.body.description是否正确获取到CKEditor提交的富文本内容,确保存储到数据库时没有被截断或篡改。
内容的提问来源于stack exchange,提问作者User101
相关产品推荐
相关产品推荐

