代码之家  ›  专栏  ›  技术社区  ›  Andy

如何从ajax响应更新ckeditor5中的内容

  •  -2
  • Andy  · 技术社区  · 7 年前

    <textarea name="content" id="editor"></textarea>
    
    <script>
    ClassicEditor
        .create( document.querySelector( '#editor' ) )
        .then( editor => {
            console.log( editor );
        } )
        .catch( error => {
            console.error( error );
        } );
    </script>
    

    <script>
        $(function() { 
            $.ajax({
                url: '/get-editor-data',
                method: 'get'
            }).done(function (response) {
                $('#editor').html(response.comment);
            });
        });
    </script>
    

    ajax请求正在成功运行并返回有效的JSON:

    {"comment":"foo"}
    

    但是我得到了一个没有任何内容的编辑器。

    如果我禁用ckeditor-通过注释掉js的第一个块( ClassicEditor... )-所以这只是一个普通文本区域,内容填充正确。

    那么如何以这种方式在编辑器中获取内容呢?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Quentin    7 年前

    the documentation

    你必须打电话 editor.setData(…); .

    你有 editor 定义如下:

    .then( editor => {
    

    因此,要将该变量保持在范围内,您需要:

    • 将整个编辑器初始化部分移动到Ajax回调中(替换 $('#editor').html(response.comment) )
    • then 回拨
    • Promise.all 并在生成的数组中获取编辑器和数据。

    注意,这不是一个实时演示,因为Stackoverflow的沙箱与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://stackoverflow.com/humans.txt",
        method: "get"
      });
    }
    
    $(function() {
      var promises = [init_editor(), get_data()];
      Promise.all(promises).then(function(results) {
        results[0].setData(results[1]);
      });
    });