models.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
uphone = db.Column(db.String(11))
def to_dict(self):
dic = {
'id': self.id
'uphone': self.uphone
}
return dic
html/demo.html
<button id="btnAjax">请求数据</button>
<table width="500" border="1">
<thead>
<tr>
<th>ID</th>
<th>电话号码</th>
</tr>
</thead>
<tbody id="body"></tbody>
</table>
javascript/demo.html
<script src="/static/js/common.js"></script>
<script src="/static/js/jquery-1.11.3.js"></script>
<script>
$(function(){
$("#btnAjax").click(function(){
var xhr = createXhr();
xhr.open('get', '/list', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var arr = JSON.parse(xhr.responseText);
var html = "";
for(var i in arr){
html += "<tr>";
html += "<td>" + arr[i].id + "</td>";
html += "<td>" + arr[i].uphone + "</td>";
html += "</tr>";
}
$("#body").html(html);
}
};
xhr.send(null);
});
});
</script>
javascript/common.js
function createXhr(){
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
views.py
@main.route("/")
def index():
return render_template("demo.html")
@main.route("/list")
def list_all():
users = User.query.all()
list = []
for u in users:
list.append(u.to_dict())
return json.dumps(list)