我正在使用CKEditor。 我正在使用页面方法通过ajax保存表单值。
但是,CKEditor的内容无法保存到表中。
我没有进行页面回发。
我该怎么办?
在实例上使用CKEditor.editor.getData()调用。也就是说:
HTML
<textarea id="my-editor">
<input id="send" type="button" value="Send">
CKEditor 4.0.x 的 JavaScript
$('#send').click(function() {
var value = CKEDITOR.instances['DOM-ID-HERE'].getData()
// send your ajax request with value
// profit!
});
CKEditor 3.6.x 的 JS
var editor = CKEDITOR.editor.replace('my-editor');
$('#send').click(function() {
var value = editor.getData();
// send your ajax request with value
// profit!
});
如果你没有像Aeon的回答中那样持有编辑器的引用,你也可以使用以下形式:
var value = CKEDITOR.instances['my-editor'].getData();
如果你没有使用已经使用JavaScript的encodeURIComponent方法进行编码的库来保存数据,而是手动完成,那么你必须记住使用encodeURIComponent来正确地编码被发送的数据。
所以你应该按照以下步骤进行:
var value = encodeURIComponent(CKEDITOR.instances['my-editor'].getData());
了解更多信息:https://ckeditor.com/docs/ckeditor4/latest/guide/dev_savedata.html
var strData = CKEDITOR.instances['editor_'+intCounter].getData();
- 如果对其他人有用的话。 - Adam Tomatvar value = CKEDITOR.instances['YourInstanceName'].getData()
alert( value);
将YourInstanceName
替换为您实例的名称,即可获得所需结果。
我在处理ajax请求时,发现getData()
有时候不能正常工作。
通过运行以下代码,我解决了这个问题:
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances[instanceName].updateElement();
}
现在有了jQuery适配器,这个答案需要更新:
假设您使用$('.ckeditor').ckeditor(opt)
初始化编辑器,然后可以使用$('.ckeditor').val()
获取值。
要获取ckeditor的数据,您需要获取ckeditor实例
HTML代码:
<textarea class="form-control" id="reply_mail_msg" name="message" rows="3" data-form-field="Message" placeholder="" autofocus="" style="display: none;"></textarea>
JavaScript:
var ck_ed = CKEDITOR.instances.reply_mail_msg.getData();
function postForm($form, callback)
{
// Get all form values
var values = {};
var fields = {};
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances[instanceName].updateElement();
}
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
// Throw the form values to the server!
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : values,
success : function(data) {
callback( data );
}
});
$('textarea').data('ckeditorInstance').getData();
<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>
使用纯净的Vanilla Javascript/Jquery或任何Javascript库:
如果您在以下文本区域中加载了Ckeditor:
<textarea name="editor1" id="editor1"></textarea>
var txtNotes = document.getElementsByClassName('ck-content')[0].innerHTML;
CKEDITOR.instances['DOM-ID-HERE'].getData();
。 - Laoujin$('.my-editor-class').val()
即可。请查看下面的答案。 - Benj