我是新來的都Symfony和阿賈克斯,我想提交表單,而無需刷新我是this教程下面沿着頁面每次,一切工作的頁面並提交到數據庫,但問題是,我在瀏覽器中得到這個信息JSON響應顯示
{"message":"Success!"}
這就是我在我的控制器中。
$bon = new Bons();
$form = $this->createForm('AppBundle\Form\BonsType', $bon);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($bon);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
return $this->render('bons/new.html.twig', array(
'bon' => $bon,
'form' => $form->createView(),
));
阿賈克斯部分:
$(document).ready(function() {
$('body').on('submit', '.myForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
alert(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
});
有沒有什麼辦法來提交表單不重定向或刷新頁面
首先你說你做了這段代碼,因爲你不想參考每次都要關閉頁面,並在底部詢問是否有方法刷新頁面......這是什麼? – Chris
哦,我沒有注意到,我其實是第一個,提交,而無需刷新 –