我正在开发一个用于网站编辑页面的界面。使用CKeditor。我想使用Ajax方法来保存修改。我的文本存储在数据库中。我使用 Doctrine 来接近他。
jQuery 脚本
$(".loading").hide();
$('[name="contentsForm"]').submit(function() {
$('[name="contentsForm"]').hide();
$("#contents .loading").show();
$.ajax({
type: "POST",
url: "{{ path('AdminAjaxEditText', {'page' : 'index', 'description' : 'contents'})}}",
data: "{'data': '" + $('#contentsForm_data').val() + "'}",
cache: false,
success: function(data){
$('[name="contentsForm_data"]').html(data);
CKupdate();
$('[name="contentsForm"]').show();
$("#contents .loading").hide();
}
});
return false;
});
Controller PHP
public function ajaxEditAction($page, $description, Request $request) {
$em = $this->getDoctrine()->getManager();
$text = $em->getRepository("FDMWebsiteBundle:Text")->find(array("page" => $page, "description" => $description));
$form = $this->get('form.factory')->createNamed($description."Form", new TextType(), $text);
if ($form->handleRequest($request)->isValid()) {
$em->flush();
}
return $this->render("Bundle:Admin:textForm.html.twig", array(
"form" => $form->createView()
));
}
模板 Twig
{{ form_start(form, {'action': ''}, {'method': 'POST'}) }}
{{ form_errors(form) }}
{{ form_widget(form.data, { 'attr': {'class': 'ckeditor'} }) }}
<input type="submit" class="saveTextBtn btn btn-primary pull-right" value="Enregistrer"/>
<div class="clearfix"></div>
{{ form_rest(form) }}
{{ form_end(form) }}
我的问题是何时单击保存 Ajax 运行但我的数据库中没有保存任何内容?
我做错了什么?
我不明白为什么我的代码没有刷新,而是在 Ajax 请求后显示在 textarea 中。
对不起我的英语,我正在学习......
最佳答案
我找到了我的问题
首先,我需要将字符集设置为 utf-8 并从 CKEditor 获取数据,而不是从文本区域获取数据
scriptCharset: "utf-8",
data: "data=" + CKEDITOR.instances['contentsForm_data'].getData()
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#getData
第二:我的ajax Controller 需要使用getter的请求。表单的handleRequest方法不起作用,我不知道为什么。如果有人能给我解释,我正在寻找它。
if($request->isXmlHttpRequest()) {
$data = $request->request->get('data');
$text->setData($data);
$em->flush();
}
教程和一些帖子使用此解决方案,但我不明白为什么 handlerResquest 失败?
第三:我需要将 CKEDITOR 配置为不使用实体
CKEDITOR.config.entities = false;
http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-entities
关于php - Symfony2如何使用学说更新发出Ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930095/