简体   繁体   中英

python with flask get and post methods using ajax

i am currently developing a food calorie web app and i want to extract data from a mongoDB into an HTML table.

my python code is:

from flask import Flask
from flask import request
import requests
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from flask import render_template, jsonify
import os
from flask import Markup
from contextlib import suppress
from collections import defaultdict
import operator
import re
from collections import Counter
import random
import math
import collections
import pymongo
from pymongo import MongoClient
from flask_table import Table, Col



app = Flask(__name__)

#jsonify(result=str(test[0]))



@app.route('/')
def index():
    return render_template('index.html')


@app.route('/_foods')
def add_numbers():
    connection = MongoClient('<connection string>')
    db = connection.foodnutr

    a = request.args.get('a', 0, type=str)
    test=[]
    for i in db.foods.find( {"Description":{'$regex': a}}):
            test.append(i)

    items = [test[0]["Description"]]



    return jsonify(result=str(test[0]['Description']))




if __name__ == '__main__':
    app.run(host='127.0.0.1', port=2490,debug=True)

and my HTML file is:

 <!DOCTYPE html> <html lang="en"> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> <script type=text/javascript> $(function() { $('#calculate').bind('click', function() { $.getJSON('/_foods', { a: $('input[name="a"]').val() }, function(data) { $("#result").text(data.result); }); return false; }); }); </script> </head> <body> <div class="container"> <div class="header"> <h3 class="text-muted">Enter a food</h3> </div> <hr/> <div> <p> <input type="text" size="5" name="a" > <input type="submit" value="Submit" onclick="myFunction()" id="calculate"> </form> </div> </div> <table id="result"> <tr> <th>id</th> <th>result</th> </tr> </table> </body> </html>

currently, i have successfully managed to get the data from the mongoDB into flask in both json, dictionary formats.

What i need, is to get my data into HTML table.

How can i achieve it?

For your current JSON use this code:

 $(function() {
    $('#calculate').bind('click', function() {
        $.getJSON('/_foods', {
            a: $('input[name="a"]').val()
        }, function(data) {
            for (key in data) {
                $('#result').append('<tr><td>' + key + '</td><td>' + data[key] + '</td></tr>')
            }
        });
        return false;
    });
});

But actually this is not nice method to implement. It would be better to change your JSON and use http://json2html.com/ jQuery plugin for building table.

Better JSON Schema:

var data = [{
    "name": "Protein(g)Per Measure",
    "value": 22.6
}, {
    "name": "Sugars, total(g)Per Measure",
    "value": 5.72
} {
    "name": "Vitamin E (alpha-tocopherol)(mg)Per Measure",
    "value": 0.0
}]

In this case using JSON2HTML is recommended:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${value}"}
        ]}
    ]}
]};

$('#result').html(json2html.transform(data,transform));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM