【发布时间】:2013-08-23 14:53:45
【问题描述】:
用 Symfony2 实现 AJAX 有我现在看到的那么难吗?
我的目标是实现一个单页应用程序,该应用程序显示一个用于创建帖子的表单(每个帖子都有一个帖子标题和一个帖子内容)。提交表单时,AJAX 负责在 div#output 中显示表单下方的帖子。
我的模板看起来像:
{% extends '::base.html.twig' %}
{% block body %}
<form action="{{ path('post_creates', { 'id': entity.id }) }}" id="form_ajax" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<input type="submit" value="create" />
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('post') }}">
Back to the list
</a>
</li>
</ul>
<div id="output"></div>
{% endblock %}
{% block javascripts %}
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://jwpsrv.com/library/leLjogZ6EeOBvCIACusDuQ.js"></script>
<script src="{{ asset('bundles/testblog/js/test2.js') }}"></script>
<script>
$("#form_ajax").submit(function(){
tinyMCE.get("test_bundle_blogbundle_posttype_postContent").save();
var content= $("#test_bundle_blogbundle_posttype_postContent").val();
var title = $("#test_bundle_blogbundle_posttype_postTitle").val();
$.ajax({
type: "POST",
url: "{{ path('post_creates', { 'id': entity.id }) }}",
data: {datas:title, date:content},
cache: false,
success: function(data){
$('#output').html(data);
}
});
return false;
});
</script>
{% endblock %}
控制器是:
public function createsAction(Request $request, $id)
{
$request = $this->container->get('request');
$entity = new Post();
if($request->isXmlHttpRequest())
{
$title = $request->request->get('datas');
$content = $request->request->get('date');
$em = $this->container->get('doctrine')->getEntityManager();
if($title != '')
{
$entity->setPostContent($content);
$entity->setPostTitle($title);
$id=$entity->getId();
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$post = $em->getRepository('TESTBlogBundle:Post')->find($id);
}
else {
$post = $em->getRepository('TESTBlogBundle:Post')->find($id);
}
$deleteForm = $this->createDeleteForm($id);
return $this->container->get('templating')->renderResponse('TESTBlogBundle:Post:show.html.twig', array(
'entity' => $post, 'id' => $id,
'delete_form' => $deleteForm->createView(),
));
}
else {
return $this->indexAction();
}
}
我有以下问题:
Controller requires that you provide a value for the "$id" argument (because there is no default value or because there is a non optional argument after this one).
当我 var_dump 控制器中的 $id 时,我总是有 null。如果我在函数参数中向它传递一个值,我的控制器工作正常。我在 Symfony2 中的知识不允许我找到我所缺少的。非常感谢您的帮助。
【问题讨论】:
-
在渲染的HTML中,你的ajax调用中
url:后面的值是什么? -
@cheesemacfly,感谢您的反馈。该值是/site/web/app_dev.php/post/creates。我看不到 id,即使我在控制器参数函数中将值传递给 $id。
-
如果您将实体转储到树枝模板中会怎样:
{{ dump(entity) }}。有id吗? -
我的意思是您应该首先查看呈现视图的控制器(包含 ajax 调用的控制器),因为这是缺少实体的控制器。
-
下面的答案已经包含解决方案,您的问题已经解决。这才是最重要的:)
标签: javascript jquery ajax forms symfony