簡體   English   中英

JQuery / Flask - 將數據從服務器發送到瀏覽器作為JSON

[英]JQuery/ Flask - send data from server to browser as JSON

首先原諒我的無知,我對這一切都很陌生。

我的問題是我正在嘗試將存儲在mongodb坐標中的json數據發送到客戶端瀏覽器。 我有一個python模塊,它使用Twitter的Streaming API存儲到數據庫中。 這工作正常,但是當我嘗試將其發送到客戶端時,它什么也沒顯示,盡管我可以看到服務器終端獲取更多數據。 我以前沒有使用Flask或JQuery,所以基於http://flask.pocoo.org/docs/patterns/jquery/上的示例。

這是我的代碼:

from flask import Flask, jsonify, render_template, request
from pymongo import Connection 

app = Flask(__name__)

@app.route('/_reader')
def reader():
    db = Connection().tstream
    coll = db.tweets_tail
    cursor = coll.find({"coordinates.type" : "Point" }, {"coordinates" :1},tailable=True,timeout=False)
    ci=0
    while cursor.alive:
        try:
            doc = cursor.next()
            ci += 1
            print doc
            print ci
        except StopIteration:
            pass
    return jsonify(ci, doc)


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

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

這是我的html客戶端:

{% extends "layout.html" %}
{% block body %}
<script type=text/javascript>
  $(function() {
       $.getJSON($SCRIPT_ROOT + '/_reader', 
       function(data) {
        $("#result").text(data.result);
      });
      return false;
    });

</script>
<h1>Coordinates</h1>
<p>
   <span id=result>?</span>
{% endblock %}

我希望收到新的坐標數據,然后將其推送到客戶端。

我希望有人可以提供幫助。

謝謝

不確定你的行返回jsonify(ci,doc)

你確定這會正確返回嗎? 參數應該是字典格式。 你可以嘗試這個嗎?

return jsonify(dict(ci=ci, doc=doc))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM