我即将提交表单使用Ajax,我已成功使用 POST 提交表单但不知道如何使用Ajax与 Symfony
builform
$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 ));
}
答案 0 :(得分:17)
使用jQuery,使用serialize()
表单并将其发布到您的路线。
$('#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')));
}
一定是这样的。但是你可以在你的路由中添加一些参数,比如格式,方法等。
答案 1 :(得分:2)
用于Ajax
$("#person").submit(function(e){
var formURL = "{{ path('form') }}";
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
e.unbind();
});
$("#person").submit();
和For Action
if ($request->isXmlHttpRequest()) {
....
return new Response(json_encode(array('status'=>'success'));
}