我有文章实体,我想通过ajax添加一篇文章。
我创建一个表单:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name')
->add('descriptions');
}
这是我的控制者:
/**
* @Route("/admin/article/add", name="app_admin_add_article")
*/
public function addCustomer(Request $request)
{
$form = $this->createForm(ArticleFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
/** @var Article $article */
$article = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
$this->addFlash('success', 'Article was successfully added!');
return $this->redirectToRoute('app_admin_articles');
}
return $this->render('admin/articles/create.html.twig', [
'articleForm' => $form->createView(),
]);
}
我该如何编写JavaScript以通过Ajax提交此表单?
答案 0 :(得分:1)
使用按钮或其他元素在HTML上调用ajax
$.ajax({
type: 'POST',
url: "{{ url('app_admin_add_article') }}",
data: {
name: document.getElementById("nameInput").value,
description: document.getElementById("descriptionInput").value
},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err);
}
});
并获取ajax在控制器中发送的数据
/**
* @Route("/admin/article/add", name="app_admin_add_article")
*/
public function addCustomer(Request $request)
{
// throw exception if not ajax call
if (!$request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
$name = $request->request->get('name');
$description = $request->request->get('description');
$article = new Article();
$article->setName($name);
$article->setDescription($description);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return new Response('Article created');
}
这只是一个基本示例,没有验证输入值并考虑您的类扩展了控制器
答案 1 :(得分:0)
我想你的ajax请求应该看起来像这样:
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
,并且您必须在阻止按钮默认设置后,使用“提交”按钮上的“点击”功能将其触发:
e.preventDefault();
,在这种情况下,您必须更改控制器逻辑。 但是,如果我可能要问,为什么要使用ajax提交?