【问题标题】:Can't get json through ajax and flask无法通过ajax和flask获取json
【发布时间】:2014-09-01 07:50:44
【问题描述】:

我正在尝试为日志显示制作一个简单的 Web 应用程序。在 Web 端:python 3.4 和 flask,在客户端,它是带有 ajax 的简单 Web 表单。

烧瓶:

import json
from flask import Flask, jsonify, render_template, request

app = Flask(__name__)

@app.route('/json_test', methods=['GET'])
def json_test():
    return open('log.json').read()


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

if __name__ == '__main__':
    app.run(debug=True)

我的 HTML 表单

<!DOCTYPE html>
<script type=text/javascript src="{{
  url_for('static', filename='jquery.js') }}"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{
  url_for('static', filename='jquery.js') }}">\x3C/script>')</script>

<script type=text/javascript>
  $LOG = {{ request.script_root|tojson|safe }};
</script>


<script type=text/javascript>
    $(function() {
        $('a#log').bind('click', function() {
            $.getJSON($LOG + '/json_test',
                function(data){
                    $("#logs").text(data.result);
                    });
                    return false;
            });
  });
</script>


<p>
    <span id=logs>Logs should be here</span>
    <a href=# id=log>take log</a>
</p>
</html>

还有我的 JSON 示例:

{
"data":
{
    "misc":
    [
        {
            "name" : "JSON 1",
            "type" : "1"
        },

        {
            "name" : "JSON 2",
            "type" : "2"
        }
    ]
}
}

我想每 5 秒发送一次日志的一部分。为此,我打算使用js函数:setInterval。我说的对吗?

【问题讨论】:

    标签: javascript jquery python ajax json


    【解决方案1】:

    您的 JSON 数据没有 result 键。你有一个data 键。

    data.data 结果放在&lt;span&gt; 中只会插入文本[object Object];您需要插入实际文本。您可以使用JSON.stringify() 将对象转回 JSON 文本:

    $("#logs").text(JSON.stringify(data.data));
    

    或者你可以发送一些更有意义的东西。

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 2012-04-10
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多