我对Ajax还是陌生的,我正尝试向Ajax和Symfony提交注册表,但是我非常执着于这样做的步骤:
在我的控制器中:
/**
* @Route("/inscription", name="security_register")
*/
public function register(Request $req, ObjectManager $manager, UserPasswordEncoderInterface $encoder)
{
$user = new UserSecurity();
$form = $this->createForm(UserRegisterType::class,$user);
$form->handleRequest($req);
if($form->isSubmitted() && $form->isValid()) {
$hash = $encoder->encodePassword($user,$user->getPassword());
$user->setPassword($hash);
$manager->persist($user);
$manager->flush();
}
return $this->render('security/register.html.twig', [
'title' => 'Doggn - S\'inscrire',
'form' => $form->createView()
]);
}
在我的app.js中
//Display the register form on the index page
const getRegisterForm = (e) =>{
e.preventDefault();
$.ajax({
url: '/inscription',
method: 'GET',
dataType: 'html'
})
.done((res)=>{
$('html').html(res)
$('.registerSubmit').on('click',handleSubmitForm)
})
.fail(()=>{
console.log('error')
})
}
//Submit the form with Ajax
const handleSubmitForm = (e) => {
e.preventDefault();
let email = $('#user_register_email').val()
let password = $('#user_register_password').val()
let confirm_password = $('#user_register_confirm_password').val()
let username = $('#user_register_username').val()
console.log(email)
console.log(password)
console.log(confirm_password)
console.log(username)
$.ajax({
url: '/inscription',
method: 'POST',
dataType: 'json',
data: {
'user_register[email]':email,
'user_register[password]':password,
'user_register_confirm_password':confirm_password,
'user_register[username]':username,
}
})
.done((res)=>{
console.log(res)
})
.fail(()=>{
console.log('ERROR ON SUBMIT')
})
}
$('#btn-connect').on('click',getRegisterForm)
在console.log中,我看到了表单的4个值,但是我真的不知道如何将它们发送到控制器。 我在handleSubmitForm中的Ajax请求没有发送数据,并向我返回了fail方法。
答案 0 :(得分:0)
您必须像这样序列化表格
Person