集成CK Editor后AJAX提交数据返回Null值的问题排查
CKEditor 提交值为 Null 的解决方案
问题核心原因:CKEditor 初始化后会隐藏原生的 <textarea>,用自定义的编辑区域替代,导致原生文本框内容不会自动同步编辑器的输入内容,FormData 读取的是原生文本框的旧值(空值)。
解决要点及代码修改:
1. 保存 CKEditor 实例
创建编辑器时需要保存实例,方便后续调用同步方法:
// 全局声明编辑器实例变量 let policyEditor; $(document).on('click','#createpolicy',function(){ $('#addeditpolicymodal').modal('toggle'); $('.addeditpolicy_title').html('Add A new Policy'); $('#savepolicy').html('Create the Policy'); // 插入文本框 $("#policy_description_ck").html('<textarea class="form-control text-white bg-dark policydesceditor" name="policy_description" placeholder="Describe the Policy Details here.explain it with as more details as possible"></textarea>'); // 初始化CKEditor并保存实例 ClassicEditor .create( document.querySelector( '.policydesceditor' ), { toolbar: { items: [ 'heading', '|', 'bold', 'italic', '|', 'link', '|', 'outdent', 'indent', '|', 'bulletedList', 'numberedList', '|', 'undo', 'redo' ], shouldNotGroupWhenFull: true } }) .then(editor => { policyEditor = editor; // 保存编辑器实例 }) .catch(error => { console.error('CKEditor初始化失败:', error); }); $("#addremovevideo").hide(); });
2. 提交前同步编辑器内容到原生文本框
在 AJAX 提交前,调用 CKEditor 的 updateSourceElement() 方法,将编辑器内容同步到对应的 <textarea>,确保 FormData 能读取到最新内容:
$('#savepolicy').click(function(e){ e.preventDefault(); var policyid=$('#policyid').val(); var url = '{{ route("createupdate.policy", ":id") }}'; policyupdateurl = url.replace(':id',policyid); // 关键步骤:同步编辑器内容到原生textarea if (policyEditor) { policyEditor.updateSourceElement(); } var form = $('#addeditpolicyform')[0]; var formdata=new FormData(form); $.ajax({ url:policyupdateurl, method:'POST', processData:false, contentType:false, data:formdata, success:function(response) { console.log(response); if (response.status==400) { $('.policy_errorlist').html(" "); $('.policy_errorlist').removeClass('d-none'); $.each(response.message,function(key,err_value) { $('.policy_errorlist').append('<li>' + err_value + '</li>'); }) } else if (response.status==200) { alertify.set('notifier','position', 'top-right'); alertify.success(response.message); policycatstable.ajax.reload(); $('.addeditcatpolicy').html(''); $('.catlabel').html(''); $('.save_button').html(''); $('.policycat_id').val(''); $('#policycat_title').val(''); $('.adminaddeditpolicy').modal('hide'); // 清空编辑器内容,方便下次使用 if (policyEditor) { policyEditor.setData(''); } } }); });
备选方案:手动赋值到文本框
如果 updateSourceElement() 方法无效,也可以手动将编辑器内容赋值给原生文本框:
if (policyEditor) { $('.policydesceditor').val(policyEditor.getData()); }
内容的提问来源于stack exchange,提问作者stephen Weru
相关产品推荐
相关产品推荐

