CKEditor,AJAX Save

问题描述 投票:6回答:10

您能否提供一个示例,说明如何使用CKEditor工具栏中的“保存”按钮设置C​​KEditor以通过AJAX进行保存?

我有兴趣创建一个CKEditor AJAX保存页面,但我们没有在他们的网站上看到任何示例。

谢谢!

ajax ckeditor
10个回答
5
投票

尝试直接从_source / plugins / save / plugin.js复制并根据需要进行更改。在/ path / to / ckeditor / plugins中创建新插件(即不在/ path / to / ckeditor / _source / plugins中)。例如,在/ path / to / ckeditor / plugins中创建一个新目录“AjaxSave”,然后在该目录中创建一个文件“plugin.js”。然后在该文件中做这样的事情(改编自源文件夹中的正常“保存”插件):

(function()
{
  var saveCmd =
  {
    modes : { wysiwyg:1, source:1 },
    exec : function( editor )
    {
      var $form = editor.element.$.form;
      if ( $form )
      {
          try
          {
            editor.updateElement();
//Here is where you put your ajax submit function. For example... if you are using
// jQuery and the ajaxform plugin, do something like this:
            $($form).ajaxSubmit({
               success: function(response){
                 //do something with the response
               }
            });
          } catch ( e ) {
            //alert(e);
          }
      }
    }
  }
  var pluginName = 'ajaxsave';
  CKEDITOR.plugins.add( pluginName,
  {
     init : function( editor )
     {
        var command = editor.addCommand( pluginName, saveCmd );
        command.modes = { wysiwyg : !!( editor.element.$.form ) };
        editor.ui.addButton( 'AjaxSave',
         {
            label : editor.lang.save,
            command : pluginName,
            icon: "/img/save.png"
         });
     }
   });
})();

然后在定义工具栏的配置中,将“AjaxSave”更改为“Save”。

编辑:你还必须添加config.extraPlugins =“ajaxsave”;到配置。


0
投票

如果元素周围没有html格式,您可能会注意到最初该按钮被禁用,不幸的是,这种行为是硬编码的。要启用它,您必须更改按钮的状态。

这是我的代码:

<script>
    function editor(domElement, callback){
        var editor = CKEDITOR.replace(domElement);
        // save-command currently unavailable because we have no form.
        editor.on('instanceReady',function(){
            // find the save-command
            var command = editor.getCommand('save');
            // set the initail state to enabled/unpressed
            command.setState(CKEDITOR.TRISTATE_OFF);
            // overwrite the exec-command
            command.exec = function (){
                var newHtml = editor.getData();
                callback(newHtml);
                editor.destroy();
            }
        });
    }
</script>

5
投票

您可以使用beforeCommandExec事件和cancel()方法:

<script type="text/javascript">
$(document).ready(function () {

    $('.ckeditoriz').ckeditor(/* config */);

    $('.ckeditoriz').each(function () {
        var id = $(this).attr('id'),
            form = this.form;

        CKEDITOR.instances[id].on('beforeCommandExec', function (event) {
            if (event.data.name === 'save') {
                event.cancel();
                $(form).submit();
            }
        });

    });

    $('.ajaxForm').submit(function (event) {
        event.preventDefault();
        var $this = $(this);
        $.ajax({
            type: $this.attr('method'),
            url: $this.attr('action'),
            data: $this.serialize()
        });
    });

});
</script>

<form action="url" method="post" class="ajaxForm">
  <!-- Your textarea must have an ID! -->
  <textarea id="textarea1" name="textarea1" class="ckeditoriz"></textarea>
</form>

更新:

这在CKEditor版本4.0,4.1,4.2中不起作用,但是从版本4.3开始它再次起作用。

从CKEditor版本4.2开始,您可以使用save事件和cancel()方法:

CKEDITOR.instances[id].on('save', function (event) {
    event.cancel();
    $(form).submit();
});

4
投票

这是我使用的方法,不需要插件:

它简单可靠,并使用内置保存按钮的CKEditors。

将一个不可见的提交按钮(display:none)添加到CKEditor所在的同一个表单中,并将其ID和Name设置为“submit”,然后当CKEditor的标准保存按钮为时,输入的onclick和表单onsubmit都将被执行。点击。您可以内联或使用jquery.bind()或任何其他方式连接事件处理程序。然后添加一个附加到表单onsubmit事件的函数来序列化表单,ajax将它发布到以'action'属性形式设置的url。只需从事件处理程序返回'False'即可确保表单不会发布。现在,提交表单的任何代码或按钮(包括ckeditor保存按钮)都将运行您的处理程序。无需CKeditor插件或CKeditor配置。这是一个简化的例子(假设是JQuery)。

<form id="myform" name="myform" action="" method="post" onsubmit="alert('form.onsubmit()');return false;">
<input type="submit" id="submit" name="submit" style="display:none" onclick="SaveText(this);"/>
<textarea id="ckeditor1"></textarea>
</form>

<script>
function SaveText (eventargs){
   var form = $(eventargs).closest("form");
   var data = form.serialize();
   var url = form.attr('action');
$.post(url, data);
return false;
}
</script>

更现实的方法可能使用JQuery.Bind(),并且脚本将在外部JS文件等中,但最终结果是相同的。它的工作原理是因为输入隐藏了表单的提交函数,因此对form.submit()的任何调用都会调用提交按钮的onclick()函数(所有浏览器的std行为)。因为它是一个“提交”按钮,它会导致表单的'onsubmit'事件触发,如果直接调用form.submit(),通常不会发生这种情况。因此,您可以在没有插件或使用CKEditor API的情况下获得可靠的松散耦合拦截保存事件。除了ajax之外,你还可以使用它,它非常适合你需要做的任何预先保存处理。


3
投票

我在这里发布了最简单的ajax保存插件Ajax save plugin for CKEDITOR 3.x with jquery 1.4.x


3
投票

已经有很多答案,但我认为我的解决方案比迄今为止的所有内容更简单,更清晰。这将使用您使用ckeditor 4指定的javascript覆盖现有保存按钮的功能:

HTML:

<textarea id="CKEditor1"></textarea>

JavaScript的:

<script>
    // Need to wait for the ckeditor instance to finish initialization
    // because CKEDITOR.instances.editor.commands is an empty object
    // if you try to use it immediately after CKEDITOR.replace('editor');
    CKEDITOR.on('instanceReady', function (ev) {

        // Create a new command with the desired exec function
        var overridecmd = new CKEDITOR.command(editor, {
            exec: function(editor){
                // Replace this with your desired save button code
                alert(editor.document.getBody().getHtml());
            }
        });

        // Replace the old save's exec function with the new one
        ev.editor.commands.save.exec = overridecmd.exec;
    });

    CKEDITOR.replace('CKEditor1');

</script>

1
投票

附加说明:如果您不想创建自己的图标,请进行更改

{ 
            label : editor.lang.save, 
        command : pluginName, 
        icon: "/img/save.png" 
     });

{ 
            label : editor.lang.save, 
            command : pluginName, 
            className: 'cke_button_save'
         });

1
投票

我在CKEditor 4上尝试了Korikulum的方法,但是它将表单发布了两次,所以我想出了这个:

$(function () {
    setTimeout(function () {
        CKEDITOR.instances.MyEditor.on('beforeCommandExec', function (event) {
            if (event.data.name === 'save') {
                event.cancel();//this does not seem to prevent the form post
                $(MyEditor).val(CKEDITOR.instances.MyEditor.getData());//copy data from the editor to the textarea
                $.ajax({
                    type: $(editorForm).attr('method'),
                    url: $(editorForm).attr('action'),
                    data: $(editorForm).serialize(),
                    success: function (data) {
                        alert(data.message);
                    }
                });
            }
        });
    }, 100);//CKEditor is heavy and needs time to initialize

    editorForm.submit = function (e) {//this is needed to prevent the 2nd post
        return false;
    };
});

MyEditor是带有ckeditor类的文本区域的id

editorForm是包装文本区域的表单的id

CKEditor在表单中初始化时会覆盖form.submit()函数,而event.cancel()似乎不会阻止表单被发布。所以我不得不用一个只返回false的函数覆盖该函数。

编辑:我忘了将新编辑的数据复制到textarea,以便它可以与表格的其余部分一起发送。


0
投票

更多一个解决方案变体,使用来自jQuery的AJAX。 1)声明函数CKEDITOR.ajaxSAVE; 2)调用它来保存textarea的更新HTML。

 CKEDITOR.ajaxSAVE = function ( editor ) {
    editor.updateElement();
    var htm = editor.getData();
    var otherParameter = '...';
    if (htm) $.ajax({
        type: "POST",
        url: "saveHtmFromCKEditor.php",
        data: { content: htm, other: otherParameter }
      }).done(function( msg ) { // string or JSON object
        if (!parseInt(msg)>0) alert( "ERROR WHEN SAVING: " + msg );
      });
    else 
      alert('EMPTY HTM. NOT SAVED');
 };

然后,为了电话,随时使用

 var oEditor = parent.main.CKEDITOR.instances['YourTextAreaID'];
 CKEDITOR.ajaxSAVE(oEditor);  

0
投票
 <textarea cols="80" id="editor1" name="editor1" rows="10"></textarea>

 <button id="save" onclick="save()"></button>

 <script type="text/javascript">
         function save() {

             var question = CKEDITOR.instances.editor1.getData();
             alert(question);

             $.ajax({
                type: 'POST',
                data: {file: question},
                url: "aiq_save.php?xyz="+question+"",
                success: function (html) {
                    alert('may be saved');
                    $("#show").html(html);
                }
            });
            return false;
 </script> 

 <div id="show"></div>

创建一个新页面aiq_save.php,然后:

<?php
    ECHO  $_GET['xyz'];

    ECHO $_POST['file'];//post method
?>

而你已经做到了。

© www.soinside.com 2019 - 2024. All rights reserved.