A synchronous data request is very much like we did with an HTML form submission.
Using AJAX to send data asynchronously
- Data request are either synchronous or async (asynchronous)
- Async data requests are requests that get sent to the server and back to the client without a page refresh.
- Async requests (AJAX requests) use one of two methods:
- XMLHttpRequest. That’s available natively on the window objects on the browser.
- Fetch (modern way)
Using XMLHttpRequest
var xhttp = new XMLHttpRequest();
description = document.getElemenyById("description").value;
xhttp.open("GET", "/todos/create?description=" + description);
xhttp.send();
XMLHttpRequest on success
Traditionally with XMLHttpRequest, we would define a function that is set equal to the onreadystatechange property on your request object.
xhttp.onreadystatechange = function() {
// this.readyState === 4, indicates that the operation on a server has already been completed.
// this.status === 200, indicates that the response was a successful response as HTTP status code 200 means a successful response.
if (this.readyState === 4 && this.status === 200) {
// on successful response
console.log(xhttp.responseText);
}
}
Using fetch
- fetch is another window object that lets you send HTTP requests.
- fetch(
,
fetch('/my/request',
method: 'POST',
// response body
body: JSON.stringify({
'description': 'some description here'
}),
// possible custom headers
headers: {
'Content-Type': 'application/json'
}
});
整个代码:
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATAbase_URI'] = 'postgres://username@localhost:5432/todoapp'
db = SQLAlchemy(app)
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(), nullable=False)
def __repr__(self):
return f''
# Ensure the tables are created for all the models that we've created and they haven't been created.
db.create_all()
@app.route('/todos/create', methods=['POST'])
def create_todo():
# get_json is that it fetches the JSON body that was sent to an object key description.
description = request.get_json()['description']
todo = Todo(description=description)
db.session.add(todo)
db.session.commit()
# return a useful JSON object that includes that description.
# jsonify will return JSON data to the client for us.
# whatever we pass in as our JSON object.
return jsonify({
'description': todo.description
})
@app.route('/')
def index():
return render_template('index.html', data=Todo.query.all())
Todo app
Something went wrong!
-
{% for d in data %}
- {{ d.description }} {% endfor %}
运行命令:
$ FLASK_APP=app.py FLASK_DEBUG=true flask run
结果:
这回就不需要refresh网页,就可以将结果显示在页面。
查看数据库:



