我需要在注册和登录表单中使用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检查其中的用户名。
答案 0 :(得分:1)
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应该没问题。
答案 1 :(得分:0)
非常感谢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)