Python Flask框架之页面跳转

IDE用的PyCharm(还是vs强大啊)。

项目结构:

2:页面:
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title><link rel="shortcut icon" href="{{ url_for('static', filename='images/lock.png')}}"/>
</head>
<body>
<div align="center">
    <div>
        <div>
            <h1>Welcome</h1>
            <form class="form" method="post" action="" onsubmit="return Login();">
                <input type="text" placeholder="Username" name="username" id="username">
                <input type="password" placeholder="Password" name="password" id="password">
                <button type="submit" id="login-button">SubmitLogin</button>
                <button type="button" id="btnlogin">ButtonLogin</button>
                <a href="infor">testhtm</a>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript" src="{{ url_for('static', filename='jquery.min.js') }} "></script>
{#<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>#}
<script type="text/javascript">
    function Login() {
        var login = false;
        var  txtname = $("#username").val();
        var txtpsw = $("#password").val();

        $.ajax({
            {#url:  "/py_login",可以#}
            url:"{{url_for("py_login") }}",{# 可以调到后台,路由名称#}
            {#data: "username=" + txtname + "&password=" + txtpsw,#}
            data:{"username":txtname,"userpswd":txtpsw},
            type: 'GET',
            contentType: 'json',{#'application/x-www-form-urlencoded',#}
            async: false,
            success: function (d) {
                alert("success!"+d)
                var status = d.status;
                if (d != "undefined" && d=="success")
                {
                     window.location.href="infor";{# 这里链接的应该是路由中的名称#}
                }
                else
                {
                    alert("登录失败!")
                }
            }
        });
        return login;
    }
</script>

</body>
</html>


3:后台FlaskWeb.py文件。

from flask import Flask, render_template, redirect, request, url_for , send_file
import pymssql

app = Flask(__name__)
# app.debug = True;
# @app.route('/')
@app.route('/')
def index():
    return render_template('login.html') # send_file('index.html')


@app.route('/py_login',methods=['GET','POST'])
def py_login():
    if request.method == 'GET':

        print(request.form)
        txtname = request.args.get('username')
        txtpswd = request.args.get('userpswd')

        if(txtname=="longdb" and txtpswd=="123"):
            return "success"  # get可以到这里
            print(url_for('/testhtm'))
            # return redirect(url_for('/testhtm'))
        else:
            return "enterfailed"

@app.route('/infor') #页面链接该路由名称
def f_infor():
    return render_template('infor.html')  # send_file('/templates/testhtm.html') #

# 函数


@app.route('/insertdata',methods=['GET','POST'])
def py_insertdata():
    # noinspection PyBroadException
    try:
        # conn = pymssql.connect(server='longdabing',user='sa',password='sasa',database='longtest')
        conn = pymssql.connect('longdabing', 'sa', 'sasa', 'longtest')
        cursor = conn.cursor()

        txtno = request.args.get('hno')
        txtname = request.args.get('hname')
        txtobject = request.args.get('hobject')
        txtscore = request.args.get('hscore')
        sql = "INSERT dbo.infor( no, name, object, score )VALUES ( '"+txtno+"','"+txtname+"','"+txtobject+"','"+txtscore+"')"
        cursor.execute(sql)
        conn.commit()  # 提交数据到数据库,否则不会插入到数据库中

        conn.close()
        return "insertok"
    except Exception as e:
        conn.rollback()  # 回滚操作
        return "insertfailed"
        raise e
    # finally:
    #   conn.close()




def getdata(sql):
    # conn = pymssql.connect(server='longdabing',user='sa',password='sasa',database='longtest')
    conn = pymssql.connect('longdabing', 'sa', 'sasa', 'longtest')
    cursor = conn.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    while row:
      print("ID=%d, No=%s, Name=%s, Object=%s, Score=%s" % (row[0], row[1], row[2], row[3], row[4]))
      row = cursor.fetchone()
    conn.close()
    return




if __name__ == '__main__':
    app.run()

注明:运行FlaskWeb.py文件时,路由longin.html页面,进入该页面后,输录入账号和密码,验证通过的话,则通过window.location.href="infor";{# 这里链接是路由中的名称#} 来跳转页面,最终还是由后台加载页面 infor.html

 

本来想在用户和密码验证通过后,用 redirect()方法跳转到 infor.html页面的,但是都失败,所以才用了window.location.href

求大神指点后台直接跳转的方法。

posted @ 2018-07-18 19:43  longdb  阅读(38812)  评论(2编辑  收藏  举报