如何根据 ajax 响应更新 ckeditor5 中的内容
How do you update content in ckeditor5 from an ajax response
ckeditor 5,v1.11.1
我已经初始化了一个编辑器如下:
<textarea name="content" id="editor"></textarea>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log( editor );
} )
.catch( error => {
console.error( error );
} );
</script>
我正在进行 ajax 调用(通过 jquery)并尝试使用响应填充编辑器:
<script>
$(function() {
$.ajax({
url: '/get-editor-data',
method: 'get'
}).done(function (response) {
$('#editor').html(response.comment);
});
});
</script>
ajax 请求 运行 成功并返回有效 JSON:
{"comment":"foo"}
所以内容"foo"应该出现在编辑器中。
但我得到的是一个没有任何内容的编辑器。
如果我禁用 ckeditor - 通过注释掉第一个 js 块 (ClassicEditor...
) - 所以它只是一个香草文本区域,内容被正确填充。
那么如何通过这种方式获取编辑器中的内容呢?
你必须打电话给editor.setData(…);
。
您在此处定义了 editor
:
.then( editor => {
... 所以要将该变量保留在范围内,您需要:
- 将整个编辑器初始化部分移动到您的 Ajax 回调中(替换
$('#editor').html(response.comment)
)
- 将整个 Ajax 调用代码移动到那个
then
回调中
- 将两个 promise 包装在
Promise.all
中,并在结果数组中获取编辑器和数据。
请注意,这不是现场演示,因为 Whosebug 的沙盒与 CKEditor 尝试使用 cookie 导致异常不兼容。
function init_editor() {
console.log(1);
return ClassicEditor
.create(document.querySelector("#editor"));
}
function get_data() {
console.log(2);
return $.ajax({
url: "https://cors-anywhere.herokuapp.com/https://whosebug.com/humans.txt",
method: "get"
});
}
$(function() {
var promises = [init_editor(), get_data()];
Promise.all(promises).then(function(results) {
results[0].setData(results[1]);
});
});
ckeditor 5,v1.11.1
我已经初始化了一个编辑器如下:
<textarea name="content" id="editor"></textarea>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
console.log( editor );
} )
.catch( error => {
console.error( error );
} );
</script>
我正在进行 ajax 调用(通过 jquery)并尝试使用响应填充编辑器:
<script>
$(function() {
$.ajax({
url: '/get-editor-data',
method: 'get'
}).done(function (response) {
$('#editor').html(response.comment);
});
});
</script>
ajax 请求 运行 成功并返回有效 JSON:
{"comment":"foo"}
所以内容"foo"应该出现在编辑器中。
但我得到的是一个没有任何内容的编辑器。
如果我禁用 ckeditor - 通过注释掉第一个 js 块 (ClassicEditor...
) - 所以它只是一个香草文本区域,内容被正确填充。
那么如何通过这种方式获取编辑器中的内容呢?
你必须打电话给editor.setData(…);
。
您在此处定义了 editor
:
.then( editor => {
... 所以要将该变量保留在范围内,您需要:
- 将整个编辑器初始化部分移动到您的 Ajax 回调中(替换
$('#editor').html(response.comment)
) - 将整个 Ajax 调用代码移动到那个
then
回调中 - 将两个 promise 包装在
Promise.all
中,并在结果数组中获取编辑器和数据。
请注意,这不是现场演示,因为 Whosebug 的沙盒与 CKEditor 尝试使用 cookie 导致异常不兼容。
function init_editor() {
console.log(1);
return ClassicEditor
.create(document.querySelector("#editor"));
}
function get_data() {
console.log(2);
return $.ajax({
url: "https://cors-anywhere.herokuapp.com/https://whosebug.com/humans.txt",
method: "get"
});
}
$(function() {
var promises = [init_editor(), get_data()];
Promise.all(promises).then(function(results) {
results[0].setData(results[1]);
});
});