如何在symfony2中提交表单ajax? [英] How to submit form ajax in symfony2?
本文介绍了如何在symfony2中提交表单ajax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我即将提交表单使用Ajax,我已成功使用 POST 提交表单,但不知道如何使用Ajax与 Symfony
I am about to submit my form Using Ajax,i have successfully submit my form using POST but don't know how to use Ajax with Symfony
建立
$builder->add('name', 'text', array('constraints' => array(new NotBlank()), 'attr' => array('placeholder' => 'Name')))
->add('gender', 'choice', array('empty_value' => 'Select Gender', 'constraints' => array(new NotBlank()), 'choices' => \AppBundle\Entity\Records::$gender_list, "required" => true))
->add('dateOfBirth', 'birthday', array('label' => 'Date Of Birth','required'=>true))
->add('image_path', 'file', array('label' => ' ','required'=>false, 'data_class' => null, 'constraints'=>array(new Assert\File( array('mimeTypes'=>$mime_types, 'maxSize'=>'2048k' )))))
->add('country_of_birth', 'entity', array('empty_value' => 'Country of Birth',
'class' => 'AppBundle\Entity\Location',
'property' => 'country',
'label' => 'Country of Birth'
))
->add('religion', 'entity', array('empty_value' => 'Select Religion',
'class' => 'AppBundle\Entity\Religion',
'property' => 'name',
'label' => 'Religion'
));
行动
$success = false;
$record_rep = new \AppBundle\Entity\Records();
$form = $this->createForm(new \AppBundle\Form\AddPersonType(), $record_rep);
if ($this->getRequest()->getMethod() == 'POST') {
$form->submit($request);
if ($form->isValid()) {
$data = $form->getData();
$file = $data->getImagePath();
$image = $file->getClientOriginalName();
$new_image_name = $this->hanldeUpload($image, $file);
$this->savetoDB($data, $record_rep, $new_image_name);
$success = true;
}
}
return $this->render('AppBundle:Homepage:add_person_form.html.twig', array('form' => $form->createView(), 'success'=>$success ));
}
推荐答案
使用jQuery,使用 serialize()
表格并将其发布到您的路线。
With jQuery, use serialize()
the form and post it to your route.
$('#form').submit(function(e) {
e.preventDefault();
var url = "{{ path('YOUR_PATH') }}";
var formSerialize = $(this).serialize();
$.post(url, formSerialize, function(response) {
//your callback here
alert(response);
}, 'JSON');
});
在你的行动中
if ($form->isValid()) {
....
return new Response(json_encode(array('status'=>'success')));
}
它必须是这样的。但你可以在你的路由中添加一些参数,如格式,方法等。
it must be ok like this. but you can add some parameters like the format, methods etc... in your routing.
这篇关于如何在symfony2中提交表单ajax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文