【问题标题】:Why wont this request follow my Tornado redirect?为什么这个请求不会跟随我的 Tornado 重定向?
【发布时间】:2012-08-25 19:17:09
【问题描述】:
<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 数据。

【问题讨论】:

    标签: javascript jquery python post tornado


    【解决方案1】:

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

    假设您打开了一个网页,然后您想从另一个页面获取数据。您在新选项卡中打开该页面,服务器端告诉它重定向到“/”,因此您在第二个选项卡中发现自己位于 index.html,但第一个仍然在同一位置。

    这正是您的 AJAX 正在做的事情。您已经告诉它获取页面的内容,当该页面发送重定向命令时,它只会获取请求重定向到的页面的内容并返回。

    因此,AJAX 返回 200 状态码表示成功,而不是 301 码表示重定向。更好的解决方案是让您的服务器回复独特的响应,浏览器可以识别并适当地重定向。这方面的一个示例可能是输出一个简单的字符串,例如redirect,它永远不会单独出现在有效输出中。然后可以适当地更改 jQuery:

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

    如果合适,这将重定向,否则输出到日志。

    【讨论】:

    • 使用 ajax 的替代方法来发出 post 请求是否有意义,以便它会自动重定向页面?
    • 你不会找到任何替代 AJAX 的方法。您必须记住,您使用它来请求内容,而不是说明。任何类似的东西都会完全一样。
    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 2017-01-24
    • 2015-12-09
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2014-10-19
    相关资源
    最近更新 更多