Javascript 如何在flask中使用JSON对象
我需要在我的注册和登录表单中使用JSON对象来使用ajax检查数据库中的数据 这是我的JSON对象:Javascript 如何在flask中使用JSON对象,javascript,python,json,ajax,flask,Javascript,Python,Json,Ajax,Flask,我需要在我的注册和登录表单中使用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 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检查其中的用户名。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));
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();
烧瓶:
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)
@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)
有很多使用jQuery的示例,但是您似乎使用的是香草JS,所以这就是我提供的答案
使用提供的代码进行编辑,现在我更好地理解了意图:
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));
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();
烧瓶:
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)
@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 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));
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();
烧瓶:
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)
@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)
有很多使用jQuery的示例,但是您似乎使用的是香草JS,所以这就是我提供的答案
使用提供的代码进行编辑,现在我更好地理解了意图:
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));
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();
烧瓶:
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)
@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。非常感谢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>
非常感谢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>
也许这些并不是最好的示例名称。当您查看JS时,JSON_sent是发送到Flask的,JSON_received是前端(AJAX)从服务器(Flask)接收的。我不知道您是在尝试发送JSON对象还是接收一个或两个。那么,我可以用变量JSON_sent(在JS代码中)编写任何内容吗?因为,我一开始什么都没有。当我试图打印flask控制台中发送的变量JSON_时,我没有收到,为什么?我只使用您的代码(没有添加内容)好的,我以为你在发送一个对象,因为你使用的是POST方法。我编辑了我的答案来澄清。你什么也不能发送。也许这些不是最好的示例名称。当你看JS时,JSON_sent是发送给Flask的,JSON_received是前端(AJAX)从服务器(Flask)接收的。我无法判断您是否尝试发送JSON对象或接收其中一个或两个。那么,我可以用变量JSON_sent(JS代码)编写任何内容吗?因为,我一开始没有任何内容。当我尝试在flask console中打印变量JSON_sent时,我没有收到任何内容,为什么?我只使用您的代码(没有添加内容)好的,我以为你在发送一个对象,因为你在使用POST方法。我编辑了我的答案以澄清问题。你什么也不能发送。是的,基本相似,但为你的模板定制。很高兴你让它为你工作,干杯!是的,基本相似,但为你的模板定制。很高兴你让它为你工作,干杯!