【问题标题】:python with flask get and post methods using ajaxpython与flask get和post方法使用ajax
【发布时间】:2016-09-18 20:07:08
【问题描述】:

我目前正在开发一个食物卡路里网络应用程序,我想将数据从 mongoDB 提取到 HTML 表中。

我的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)

我的 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>

目前,我已经成功地将 mongoDB 中的数据以 json 和字典格式导入到烧瓶中。

我需要的是将我的数据放入 HTML 表格中。

我怎样才能实现它?

【问题讨论】:

  • 你能把json的输出写在这里吗?
  • 示例输出为:{'Protein(g)Per Measure': 22.6, 'Sugars, total(g)Per Measure': 5.72, 'Vitamin E (alpha-tocopherol)(mg)Per Measure':0.0,'Copper, Cu(mg)Per Measure':0.162,'Vitamin D (D2 + D3)Per Measure':0.0,'Description':“ARBY'S,烤牛肉三明治,经典”,'能量(kcal )Per Measure': 361.0, 'Lactose(g)Per Measure': 0.0, 'Glutamic acid(g)Per Measure': 0.0} 但我的目的是用这个 json 输出制作一个表格。我知道我可以以某种方式在 javascript 上输出这个输出,但经过多次尝试,我不能

标签: javascript jquery python html flask


【解决方案1】:

对于您当前的 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;
    });
});

但实际上这不是很好的实现方法。最好更改您的 JSON 并使用 http://json2html.com/ jQuery 插件来构建表格。

更好的 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
}]

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

【讨论】:

  • 谢谢!!它工作正常。我也会考虑改变json格式
  • 使用第一个实现,jquery正在接收数据,但数据对象的行为似乎是字符串而不是dict。这怎么能解决?我的意思是最后一个 for 循环不能遍历字典键,并且作为 data[key] 我接收所有的 json 对象。提前致谢!
  • 我解决了。我只是将 jsonify(result=str(test[0])) 更改为 return jsonify(**test[0])