用 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).
当我在控制器中对 $id 进行 var_dump 时,我总是有 null。如果我在函数参数中向它传递一个值,我的控制器工作正常。我在 Symfony2 中的知识不允许我找到我所缺少的。非常感谢您的帮助。