目前我在我的index.html.twig文件中有一個新的操作。Symfony:ajax表單加載
<div id="formcontent">
form content goes here
</div>
<a href="{{ path('uni_new') }}">Create a new uni</a>
和我的新的行動看起來像這樣
/**
* Creates a new uni entity.
*
* @Route("/new", name="uni_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$uni = new Uni();
$form = $this->createForm('AppBundle\Form\UniType', $uni);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($uni);
$em->flush($uni);
return $this->redirectToRoute('uni_show', array('id' => $uni->getId()));
}
return $this->render('uni/new.html.twig', array(
'uni' => $uni,
'form' => $form->createView(),
));
}
我想通過Ajax請求來完成這個新動作。所以,當用戶點擊Create a new uni
,而不是去一個新的網址,我希望通過ajax調用加載表單,並替換上面的div的內容,編號爲formcontent
。我怎樣才能做到這一點?提前致謝。
您顯示的PHP代碼總體上是OK的,您需要的是以JS爲中心的,並且與Symfony無關。你應該在那裏添加你的JS代碼。 – lsouza