CKEditor、AJAX 保存

发布于 2024-08-16 04:21:09 字数 135 浏览 3 评论 0原文

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

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

谢谢!

Can you provide an example on how to setup CKEditor to save via AJAX using the Save button in the CKEditor toolbar?

I'm interested in creating a CKEditor AJAX save page but am not seeing any examples on their site.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

天邊彩虹 2024-08-23 04:21:09

您可以使用 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.04.14.2,但自版本 4.3 起它再次可用。

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

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

You can use the beforeCommandExec event & cancel() method:

<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>

Update:

This doesn't work in CKEditor versions 4.0, 4.1, 4.2, however it works again since version 4.3.

Since CKEditor version 4.2 you can use the save event with the cancel() method:

CKEDITOR.instances[id].on('save', function (event) {
    event.cancel();
    $(form).submit();
});
乞讨 2024-08-23 04:21:09

尝试直接从 _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”更改为“保存”。

编辑:您还必须添加
config.extraPlugins = "ajaxsave";
到配置。

Try copying straight from _source/plugins/save/plugin.js and changing as needed. Create your new plugin in /path/to/ckeditor/plugins (i.e. Not in /path/to/ckeditor/_source/plugins). For example, in /path/to/ckeditor/plugins create a new directory "AjaxSave", then in that directory create a file "plugin.js". Then in that file do something like this (adapted from the normal "save" plugin in the source folder):

(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"
         });
     }
   });
})();

Then in the config, where you define your toolbar, change 'AjaxSave' for 'Save'.

EDIT: you must also add
config.extraPlugins = "ajaxsave";
to the config.

掩于岁月 2024-08-23 04:21:09

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

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

在 CKEditor 所在的同一个表单中添加一个不可见的提交按钮(display:none),并将其 ID 和名称设置为“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() 函数(所有浏览器的标准行为)。因为它是一个“提交”按钮,所以它会触发表单的“onsubmit”事件,如果直接调用 form.submit(),通常不会发生这种情况。因此,您无需插件或使用 CKEditor API 即可获得可靠的松散耦合的保存事件拦截。除了ajax保存之外,您还可以使用它,它对于您需要执行的任何预保存处理都很有用。

This is the method I use, no plugins required:

It's simple and reliable and uses the CKEditors built in save button.

Add a non-visible submit button (display:none) to the same form where the CKEditor is and set it's ID and Name to "submit" then both the input's onclick and the forms onsubmit will both be executed when the CKEditor's standard save button is clicked. you can hook up your event handlers inline or with jquery.bind() or any other way. Then add a function attached to the forms onsubmit event to serialize the form and ajax post it to the url set in the form 'action' attribute. Just return 'False' from the event handler to ensure the form does not post. Now any code or button (including the ckeditor save button) that submits the form will run your handler instead. No CKeditor plugins or CKeditor configuration required.
Here's a simplified example (assumes 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>

A more realistic approach might use JQuery.Bind() and the script would be in an external JS file etc. but the end result is the same. It works because the input hides the form's submit function so any call to form.submit() calls the submit button's onclick() function instead (std behavior for all browsers). Because it's a 'submit' button it causes the form's 'onsubmit' event to fire which would not normally happen if you called form.submit() directly. so you get reliable loosely coupled interception of the save event without plugins or using the CKEditor API. you can use it for more than ajax save too, its nice for any pre-save processing you need to do.

梦幻的味道 2024-08-23 04:21:09

我在这里发布了最简单的ajax保存插件
CKEDITOR 3.x 的 Ajax 保存插件使用 jquery 1.4.x

I have posted the simplest ajax save plugin here
Ajax save plugin for CKEDITOR 3.x with jquery 1.4.x

老子叫无熙 2024-08-23 04:21:09

已经有很多答案,但我认为我的解决方案比到目前为止这里的所有解决方案都更简单、更干净。这将简单地使用您在 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>

Lots of answers already but I think my solution is way easier and cleaner than everything here so far. This will simply override the existing save button's functionality with javascript that you specify with ckeditor 4:

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>
呆° 2024-08-23 04:21:09

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

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

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

Additional Note: If you don't want to create your own Icon, change

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

to

{ 
            label : editor.lang.save, 
            command : pluginName, 
            className: 'cke_button_save'
         });
仙气飘飘 2024-08-23 04:21:09

我在 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 覆盖表单.submit() 函数在表单中初始化时, event.cancel() 似乎不会阻止表单被发布。所以我必须用只返回 false 的函数重写该函数。

编辑:我忘记将新编辑的数据复制到文本区域,以便它可以与表单的其余部分一起发送。

I've tried Korikulum's method on CKEditor 4 but it posts the form twice so I've come up with this:

$(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 is the id of the text area with ckeditor class

editorForm is the id of the form that wraps the text area

CKEditor overrides form.submit() function when it's initialized within a form and event.cancel() does not seems to prevent the form being posted. So I had to override the function with one that just returns false.

EDIT: I forgot to copy the newly edited data to the textarea so it could be sent along with the rest of the form.

朦胧时间 2024-08-23 04:21:09

更多一种解决方案变体,使用 jQuery 的 AJAX。 1)声明函数CKEDITOR.ajaxSAVE; 2) 调用它来保存文本区域的更新 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);  

More one solution variation, using AJAX from jQuery. 1) declare the function CKEDITOR.ajaxSAVE; 2) call it for save updated HTML of the textarea.

 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');
 };

Then, for call, at any time, use

 var oEditor = parent.main.CKEDITOR.instances['YourTextAreaID'];
 CKEDITOR.ajaxSAVE(oEditor);  
只是我以为 2024-08-23 04:21:09
 <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
?>

您就完成了。

 <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>

Create a new page aiq_save.php, then:

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

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

And you've done it.

剩余の解释 2024-08-23 04:21:09

如果元素周围没有 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>

If you have no html-form around the element you may notice that initially the button is disabled, this behave is unfortunately hardcoded. To enable it you must change the state of the button.

This is my code:

<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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文