简体   繁体   English

python与flask get和post方法使用ajax

[英]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.我目前正在开发一个食物卡路里网络应用程序,我想从 mongoDB 中提取数据到一个 HTML 表中。

my python code is:我的python代码是:

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:我的 HTML 文件是:

 <!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.目前,我已经成功地将 mongoDB 中的数据以 json 和字典格式获取到烧瓶中。

What i need, is to get my data into HTML table.我需要的是将我的数据放入 HTML 表格中。

How can i achieve it?我怎样才能实现它?

For your current JSON use this code:对于您当前的 JSON,请使用以下代码:

 $(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.最好更改您的 JSON 并使用http://json2html.com/ jQuery 插件来构建表。

Better JSON Schema:更好的 JSON 架构:

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:在这种情况下,建议使用 JSON2HTML:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “ GET”获取脚本文本,“ POST”导致“ 405方法不允许”,我_did_ methods = [&#39;GET&#39;,&#39;POST&#39;](从JavaScript到Flask到Python) - “GET” get text of script, “POST” results in “405 method not allowed”, I _did_ methods=['GET', 'POST'] (from JavaScript through Flask to Python) 如何使用ajax重复从python flask服务器获取数据? - How to repeatedly get data from a python flask server using ajax? Flask中的render_template返回未在使用POST和GET的方法中运行 - return render_template in flask isn't running in methods using POST and GET 使用AJAX进行GET和POST - GET and POST using AJAX 使用 ajax (JavaScript) 和 flask (Python) 进行发布时出现错误 GET 400 (BAD REQUEST) - ERROR GET 400 (BAD REQUEST) when doing post with ajax (JavaScript) & flask (Python) Transcrypt:如何发送ajax POST请求以使用Python / Flask启动服务器端作业 - Transcrypt: How to send an ajax POST request to start a server side job using Python / Flask Python flask cors POST 失败但 GET 通过 - Python flask cors failing for POST but passing for GET 此路由不支持 POST 方法。 支持的方法:GET、HEAD。 尝试使用 ajax 将数据发送到 controller - The POST method is not supported for this route. Supported methods: GET, HEAD. Trying to send data to controller using ajax 使用POST和AJAX获取数据 - Get data using POST and AJAX AJAX-使用POST而不是GET - AJAX - Using POST instead of GET
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM