【问题标题】:How to work with JSON object in flask如何在烧瓶中使用 JSON 对象
【发布时间】:2018-06-16 01:19:10
【问题描述】:

我需要在我的注册和登录表单中使用 JSON 对象来使用 ajax 检查数据库中的数据。

这是我的 JSON 对象:

@app.route('/test', methods=['POST'])
def test():
users = User.query.all()
users_schema = UserSchema(many=True)
output = users_schema.dump(users).data
jsonobj = jsonify({'users': output})
return jsonobj

我的注册表:

<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
<div class="well">
    <h1>Sign Up</h1>
    <form action="" method="post" name="regform" onsubmit="return Validate()">
    <div id="username_div">
        {{ form.hidden_tag() }}
        {{ form.username.label }}
        {{ form.username }}
        <div id="name_error"></div>
    </div>
    <div id="email_div">
        {{ form.hidden_tag() }}
        {{ form.email.label }}
        {{ form.email }}
        <div id="email_error"></div>
    </div>
    <div id="password_div">
        {{ form.hidden_tag() }}
        {{ form.password.label }}
        {{ form.password }}
        <div id="password_error"></div>
    </div>
    <div id="pass_confirm_div">
        {{ form.hidden_tag() }}
        {{ form.password_confirm.label }}
        {{ form.password_confirm }}
        <div id="password_error"></div>
    </div>
    <div>
        <input type="submit" name="register" value="Register" class="btn">
    </div>
</form>
    <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
    <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
<script src="{{ url_for('static', filename = 'js/regform_validator.js') }}"></script>
 {% endblock %}

如何将我的 JSON 对象与 ajax 一起使用?或者我可以重写我的 regform_validator.js 脚本吗?

// SELECTING ALL TEXT ELEMENTS
var username = document.forms['regform']['username'];
var email = document.forms['regform']['email'];
var password = document.forms['regform']['password'];
var password_confirm = document.forms['regform']['password_confirm'];
// SELECTING ALL ERROR DISPLAY ELEMENTS
var name_error = document.getElementById('name_error');
var email_error = document.getElementById('email_error');
var password_error = document.getElementById('password_error');
// SETTING ALL EVENT LISTENERS
username.addEventListener('blur', nameVerify, true);
email.addEventListener('blur', emailVerify, true);
password.addEventListener('blur', passwordVerify, true);
// validation function
function Validate() {
// validate username
if (username.value == "") {
username.style.border = "1px solid red";
document.getElementById('username_div').style.color = "red";
name_error.textContent = "Username is required";
username.focus();
return false;
}
// validate username
if (username.value.length < 3) {
username.style.border = "1px solid red";
document.getElementById('username_div').style.color = "red";
name_error.textContent = "Username must be at least 3 characters";
username.focus();
return false;
}
// validate email
if (email.value == "") {
email.style.border = "1px solid red";
document.getElementById('email_div').style.color = "red";
email_error.textContent = "Email is required";
email.focus();
return false;
}
// validate password
if (password.value == "") {
password.style.border = "1px solid red";
document.getElementById('password_div').style.color = "red";
password_confirm.style.border = "1px solid red";
password_error.textContent = "Password is required";
password.focus();
return false;
}
// validate password
if (password.value.length < 3) {
password.style.border = "1px solid red";
document.getElementById('password_div').style.color = "red";
password_confirm.style.border = "1px solid red";
password_error.textContent = "Password must be at least 3 characters";
password.focus();
return false;
}
// check if the two passwords match
if (password.value != password_confirm.value) {
password.style.border = "1px solid red";
document.getElementById('pass_confirm_div').style.color = "red";
password_confirm.style.border = "1px solid red";
password_error.innerHTML = "The two passwords do not match";
return false;
}
}
// event handler functions
function nameVerify() {
if (username.value != "") {
username.style.border = "1px solid #5e6e66";
document.getElementById('username_div').style.color = "#5e6e66";
name_error.innerHTML = "";
return true;
}
}
function emailVerify() {
if (email.value != "") {
email.style.border = "1px solid #5e6e66";
document.getElementById('email_div').style.color = "#5e6e66";
email_error.innerHTML = "";
return true;
}
}
function passwordVerify() {
if (password.value != "") {
password.style.border = "1px solid #5e6e66";
document.getElementById('pass_confirm_div').style.color = "#5e6e66";
document.getElementById('password_div').style.color = "#5e6e66";
password_error.innerHTML = "";
return true;
}
if (password.value === password_confirm.value) {
password.style.border = "1px solid #5e6e66";
document.getElementById('pass_confirm_div').style.color = "#5e6e66";
password_error.innerHTML = "";
return true;
}
}

我的 JSON 对象如下所示:

{
"users": [
{
  "about_me": null,
  "email": "zurgs@bk.ru",
  "followed": [],
  "followers": [],
  "id": 1,
  "last_seen": "2018-01-06T11:34:20.021696+00:00",
  "password": "pbkdf2:sha256:50000$bRcLhY9k$f26dad7b850c8b99b21f4b65f8719294417f37bf648bb12bcf6be8977b6341f1",
  "posts": [],
  "role": "user",
  "username": "ZuRGs"
},
{
  "about_me": null,
  "email": "polina@bk.ru",
  "followed": [],
  "followers": [],
  "id": 2,
  "last_seen": "2018-01-05T18:52:01.895612+00:00",
  "password": "pbkdf2:sha256:50000$em5pCjoZ$ed9bba487cce0c755eccf1575ed9b777d15708c64669193ac078331da8b65edc",
  "posts": [],
  "role": "user",
  "username": "Polina"
}
]
}

这个 JSON 对象是我的数据库,我需要使用 ajax 检查其中的用户名。

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    非常感谢 jwebb,但对我不起作用 :( 我的模板中有一些代码对我有用:

    <button onclick="loadJSON()">Show usernames in database</button>
    <script>
        function loadJSON() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/test', false);
            xhr.send();
            if (xhr.status != 200) {
            // обработать ошибку
                alert('Ошибка ' + xhr.status + ': ' + xhr.statusText);
            } else {
            // вывести результат
                var jsonobj = JSON.parse(xhr.responseText, function(key, value) {
                if (key == 'username')
                    alert(value);
                });
            }
        }
    </script>
    

    还有我的烧瓶代码:(我使用的是烧瓶棉花糖)

    @app.route('/test', methods=['GET'])
    def test():
        try:
            users = User.query.all()
            users_schema = UserSchema(many=True)
            output = users_schema.dump(users).data
            return jsonify({'users': output})
        except Exception as e:
           print('AJAX excepted ' + str(e))
           return str(e)
    

    【讨论】:

    • 是的,所以基本相似,但为您的模板定制。很高兴你让它为你工作,干杯!
    【解决方案2】:

    Flask 中典型的 AJAX POST 请求如下所示:

    JavaScript:

    var xhr = new XMLHttpRequest();
    var JSON_sent = {"your": "JSON"};
    xhr.open('POST', '/ajax-route');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var JSON_received = JSON.parse(xhr.responseText);
            //handle received JSON here
        } else {
            console.log(xhr.responseText);
        }
    };
    xhr.send(JSON.stringify(JSON_sent));
    

    烧瓶:

    from flask import jsonify, request
    
    
    @app.route('/ajax-route', methods=['POST'])
    def ajax_route():
        try:
            JSON_sent = request.get_json()
            print(JSON_sent)
            # handle your JSON_sent here
            # Pass JSON_received to the frontend
            return jsonify(JSON_received)
        except Exception as e:
            print("AJAX excepted " + str(e))
            return str(e)
    

    有很多使用 jQuery 的示例,但您似乎使用的是 vanilla JS,所以这就是我提供的答案。

    https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-ajax

    http://flask.pocoo.org/docs/0.12/patterns/jquery/

    使用现在提供的代码进行编辑,因为我更好地理解了意图:

    JavaScript:

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/test');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var jsonobj = JSON.parse(xhr.responseText);
            //handle received JSON here
        } else {
            console.log(xhr.responseText);
        }
    };
    xhr.send();
    

    烧瓶:

    @app.route('/test', methods=['POST'])
    def test():
        try:
            users = User.query.all()
            users_schema = UserSchema(many=True)
            output = users_schema.dump(users).data
            jsonobj = jsonify(users=output)
            return jsonobj
        except Exception as e:
            print("AJAX excepted " + str(e))
            return str(e)
    

    此外,如果您不发送任何内容,则 GET 请求而不是 POST 应该没问题。

    【讨论】:

    • 也许这些不是最好的样本名称。当您查看 JS 时,JSON_sent 是发送到 Flask 的内容,而 JSON_received 是前端 (AJAX) 从服务器 (Flask) 接收的内容。我不知道您是在尝试发送 JSON 对象还是接收一个或两者。
    • 那么,我可以在变量 JSON_sent 中写任何东西(在 JS 代码中)吗?因为,一开始我什么都没有。
    • 当我尝试在烧瓶控制台中打印变量 JSON_sent 时,我收到 None,为什么?我只使用你的代码(没有我的补充)
    • 好的,我以为您正在发送一个对象,因为您使用的是 POST 方法。我编辑了我的答案以澄清。你可以什么都不发送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2013-07-27
    • 1970-01-01
    相关资源
    最近更新 更多