私はsymfonyとajaxの両方に新しいので、私は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(),
));
Ajaxの一部:
$(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
ああ、私は気づかなかった、私は実際に最初のことを意味し、爽やかでなく提出した。 –