Issue
I have a users column and i am trying to output all of its data on an html file via json and ajax. i am able to return multiple columns from a single row. But i am unable to figure out how to return and call multiple rows.
Here is my code and also a couple of commented thing i have tried.
@app.route('/test', methods=['POST', 'GET'])
def test():
#thisworks
works = user.query.filter_by(name = 'foo').first()
return jsonify(name = works.name, id = works.id)
#BELOW LINES DONT WORK
#st = user.query.all()
#for i in st:
#jsonify(id = st.id[i] , name = st.username[i])
Also , will i have to call this in jquery with a for loop or a dictionary inside a dictionary.?
Please do help me with this Thanks.
Solution
The idea here is to put all the data you need in a list/array before you jsonify. Using your example:
st = user.query.all()
all_users = [{'name':user.name,'id':user.id} for user in st]
return jsonify(all_users)
Hope this helps
To use the results in jquery, you can do some thing like this
$.get('mysite.com/users').then(function(response) { // ajax to get users
users = response; // save to variable
$.each(users, function(key, val) { // iterate over result
console.log(val.id);
console.log(val.name)
});
});
Answered By - sea
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.