首页 > 解决方案 > 使用 css 将 Jsonify 返回到 html 页面

问题描述

我目前正在开发一个处理用户登录的 FLASK 应用程序。它背后的想法是,当用户输入他的登录凭据时,表单会将他的信息发送到一个 API,该 API 将确定登录是否成功。API 将发送一条消息以显示它是否成功。API 和模板页面工作正常,我可以使用 jsonify 返回消息,但我想将 jsonify 数据返回到一个 html 页面,该页面具有我的 css 设计并扩展了我的“base.html”这是我到目前为止的内容:

我的登录 API

def index():
code, message = "ERROR", "Invalid Credentials"
loginid = str(request.form.get('id')) or ''
pw = str(request.form.get('pw')) or ''

if len(loginid) == 0 or len(pw) == 0:
    # Fields not filled
    message = "Please fill in all required fields"
    return jsonify({"code": code, "message": message})


if get_user(loginid, pw):
    # Authentication Sucessful
    code, message = "OK", "Authentication successful."
    regen_session()

    session['auth'] = True
    session['user'] = loginid
    return jsonify({"code": code, "message": message})

# User credentials error
return jsonify({"code": code, "message": message})

有人可以告诉我如何将 jsonify 对象返回到包含我的 html 和 css 的页面吗?谢谢您的帮助。

标签: jsonflask

解决方案


我总是使用 JSON dataType 在客户端和服务器之间使用 javascript 进行通信。

我在这里提供工作示例:

HTML部分和jquery ajax:

    <input type="text" id="id_field">
    <input type="password" id="pass_field">
    <button type="button" onclick="sendData()">ok</button> 

    <script>
    function sendData (){
    var get_id = document.getElementById("id_field").value
    var get_pass = document.getElementById("pass_field").value

            $.ajax({
                type: "POST",
                url: "{{url_for('index')}}",
                data: JSON.stringify({id: get_id,pw: get_pass}),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function(data){
                    //handle response here      
                },
                error: function(data){
                   //handle errors here
                }
            });
    }
</script>

烧瓶部分:

@app.route('/index', methods=['POST']) 
def index():
    if request.method == 'POST':
        loginid = request.json.get('id')
        pw = request.json.get('pw')

        # do whatever with data then return jsonify data to ajax function

        return jsonify({"code": code, "message": message})

推荐阅读