如何在Symfony2网站上实施AJAX? [英] How to implement AJAX on a Symfony2 website?
问题描述
我正在尝试在一个简单的网站中实现此目的,以节省我的钱支出.因此,我希望能够在不刷新页面的情况下保存数据.
I am trying to implement this in a simple website that I save my money expenses. So I want to be able to save my data without refreshing the page.
控制器:
namespace yz\BstBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use yz\BstBundle\Entity\Money;
use yz\BstBundle\Form\MoneyType;
/**
* Money controller.
*
*/
class MoneyController extends Controller
{
/**
* Lists all Money entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('yzBstBundle:Money')->findAll();
return $this->render('yzBstBundle:Money:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Money entity.
*
*/
public function createAction(Request $request)
{
$entity = new Money();
$form = $this->createForm(new MoneyType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('money_show', array('id' => $entity->getId())));
}
return $this->render('yzBstBundle:Money:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Displays a form to create a new Money entity.
*
*/
public function newAction()
{
$entity = new Money();
$form = $this->createForm(new MoneyType(), $entity);
return $this->render('yzBstBundle:Money:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Money entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('yzBstBundle:Money')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Money entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('yzBstBundle:Money:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), ));
}
/**
* Displays a form to edit an existing Money entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('yzBstBundle:Money')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Money entity.');
}
$editForm = $this->createForm(new MoneyType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('yzBstBundle:Money:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Edits an existing Money entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('yzBstBundle:Money')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Money entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new MoneyType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('money_edit', array('id' => $id)));
}
return $this->render('yzBstBundle:Money:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Money entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('yzBstBundle:Money')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Money entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('money'));
}
/**
* Creates a form to delete a Money entity by id.
*
* @param mixed $id The entity id
*
* @return Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
树枝模板:
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Money creation</h1>
<form action="{{ path('money_create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('money') }}">
Back to the list
</a>
</li>
</ul>
{% endblock %}
表单类型
namespace yz\BstBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MoneyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('created_at')
->add('type')
->add('price')
->add('comment')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'yz\BstBundle\Entity\Money'
));
}
public function getName()
{
return 'yz_bstbundle_moneytype';
}
}
推荐答案
要回答您的问题已更改,以下是针对您的情况的解决方案:
To answer your question changed, here is a solution to your case:
控制器:
/**
* Creates a new Money entity.
*
*/
public function createAction(Request $request)
{
$entity = new Money();
$form = $this->createForm(new MoneyType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
if($request->isXmlHttpRequest()) {
$response = new Response();
$output = array('success' => true, 'type' => $entity->getType(), 'id' => $entity->getId(), 'comment' => $entity->getComment(), 'price' => $entity->getPrice());
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect($this->generateUrl('money_show', array('id' => $entity->getId())));
}
return $this->render('yzBstBundle:Money:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
模板
{% extends '::base.html.twig' %}
{% block body %}
<h1>Money creation</h1>
<form action="{{ path('money_create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('money') }}">
Back to the list
</a>
</li>
</ul>
<div id="result"></div>
{% endblock %}
{% block javascripts %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$().ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var $url = $(this).attr('action');
var $data = $(this).serialize();
$.ajax({
type: "POST",
url: $url,
data: $data
}).done(function( result ) {
if(result.success) {
$('#result').html('<span>Monetary expense correctly saved!<br/> The data are:<br/>id: '+ result.id +'<br/>type: '+ result.type +'<br/>price: '+ result.price +'<br/>comment: '+ result.comment +'</span>');
}
});
});
});
</script>
{% endblock %}
此解决方案功能全面,随着时间的推移,您将学到许多替代方法来加快处理速度,例如使用类JsonResponse()或适用于将对象序列化为JMS Serializer Bundle的大型捆绑软件.
This solution is fully functional, with time you will learn many alternative methods to speed things such as using the class JsonResponse() or a great bundle appropriate to serialize objects as JMS Serializer Bundle...
但是我们不要放太多肉!
But we don't put too many meat to the fire!
希望您能为您服务!
我输错了$entity-getPrice()
而不是$entity->getPrice()
.
ajax调用中的类型必须为POST.
The type in the ajax call must be POST.
请记住,如果尚未输入,请在控制器的开头输入以下行:
Remember to enter, if you have not already done so, this line at the beginning of the controller:
use Symfony\Component\HttpFoundation\Response;
现在它可以正常工作了.
Now it works perfectly.
这篇关于如何在Symfony2网站上实施AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!