2012-08-31 38 views
2
<html> 
<head> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js"></script> 
<title> 
Login page 
</title> 
</head> 
<body> 
<h1 style="font-family:Comic Sans Ms;text-align"="center";font-size:20pt; 
color:#00FF00;> 
Simple Login Page 
</h1> 
<form name="login"> 
Username<input type="text" name="userid"/> 
Password<input type="password" name="pswrd"/> 
<input type="button" onclick="check(this.form)" value="Login"/> 
<input type="reset" value="Cancel"/> 
</form> 
<script language="javascript"> 
function check(form) 
{ 
    $.ajax({ 
    type: 'POST', 
    url: '/auth/login', 
    data: { 
     'UserName': form.userid.value, 
     'Password': form.pswrd.value // <-- the $ sign in the parameter name seems unusual, I would avoid it 
    }, 
    success: function(msg){ 
     console.log(msg); 
    } 
}); 
} 
</script> 
</body> 
</html> 

龙卷风代码: 类MainHandler(BaseHandler): @ tornado.web.authenticated 高清得到(个体经营): self.render( “index.html的”)为什么不按照我的龙卷风重定向请求?

class AuthLoginHandler(BaseHandler): 
    @tornado.web.asynchronous 
    def get(self): 
     self.render("login.html") 

    def post(self): 
     username = self.get_argument("UserName",strip = True) 
     password = self.get_argument("Password",strip = True) 
     user = auth_actions.do_login(db,username,password) 
     if not user: 
      raise tornado.web.HTTPError(500, "Authentication Failed") 
     self.set_secure_cookie("user", tornado.escape.json_encode(user)) 
     self.redirect("/") 

我送重定向请求,而不是浏览器重定向它只是获取msg中index.html的html数据。

回答

4

您正在使用AJAX检索页面,而不是命令。

想象一下你有一个网页打开,那么你想从另一个页面获取数据。您在新选项卡中打开该页面,服务器端会告诉它重定向到“/”,因此您在第二个选项卡中找到index.html,但第一个选项卡保留在相同位置。

这正是你的AJAX所做的。你已经告诉它获取页面的内容,并且当该页面发送重定向命令时,它只是获取请求被重定向到的页面内容,然后返回该内容。

由于这个原因,AJAX返回一个200状态码以取得成功,而不是301代码用于重定向。更好的解决方案是让服务器回复唯一的响应,浏览器可以识别并适当地重定向。一个例子就是输出一个简单的字符串,比如redirect,这个字符串在有效输出中永远不会出现。然后,jQuery可以进行相应的更改:

success: function(msg){ 
    if (msg=='redirect') { 
     //Redirect to the index 
    } 
    else { 
     console.log(msg); 
    } 
} 

这将在适当的情况下重定向,否则将输出到日志。

+0

使用ajax的替代方法发出发布请求是否有意义,以便它会自动重定向页面? – carboncomputed

+0

你不会找到任何替代AJAX的东西,你必须记住你正在使用它来请求内容,而不是说明。任何类似的东西都会完全一样。 – Death

+0

这里是[解释如何执行重定向本身的答案](http://stackoverflow.com/a/506004/1599229)。 – bahmait