[英]Symfony2 redirect in an ajax action
I am using Symfony2 and in my register.html.twig, I have: 我正在使用Symfony2,在我的register.html.twig中,我有:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
}
});
In my controller, after inserting those data into the database, I want to redirect to the login page, and I have code like this: 在我的控制器中,将这些数据插入数据库后,我想重定向到登录页面,并且有如下代码:
try
{
$this -> insertData($account);
return $this ->redirect($this ->generateUrl('login'));
}
catch (Exception $e)
{
return new response('Message: '. $e->getMessage());
}
It does not work, however. 但是,它不起作用。 How should I handle the problem? 我应该如何处理这个问题?
You need another more step in your jQuery code. 您需要在jQuery代码中再走一步。 When the server returns a redirect response, you should redirect the client using javascript: 当服务器返回重定向响应时,您应该使用javascript重定向客户端:
var registerdata= {
"email": email,
"pwd": pwd,
"phoneNum": phoneNum
};
$.ajax({
type: 'POST',
url: "register",
data: registerdata,
success: function(msg){
alert("OK! ");
},
error: function(XmlHttpRequest,textStatus, errorThrown){
alert("Failed! ");
},
complete: function(xhr)
{
if (xhr.status == 302) {
location.href = xhr.getResponseHeader("Location");
}
}
});
Of course this is far from ideal. 当然,这远非理想。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.