【问题标题】:ajax json query directly to python generated html gets undefined直接对python生成的html的ajax json查询未定义
【发布时间】:2015-03-13 05:34:51
【问题描述】:

我已经苦苦挣扎了三个星期,而且我已经走到了死胡同。系统管理员是 s*tty 开发人员:)

我正在尝试构建轻量级 cgi-bin python 脚本来收集数据并将其转换为 json 格式。 然后我使用纯 html 页面对 python 脚本进行 ajax 查询以获取数据并绘制我的图表(定期,人们喜欢实时的东西)

这些应该尽可能轻,因为它们适用于覆盆子。

我收集数据的 python 脚本之一

#!/usr/bin/python

import sqlite3
import gviz_api

# enable debugging
import cgitb
cgitb.enable()

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

connection = sqlite3.connect("templog.db")
connection.row_factory = dict_factory
cursor = connection.cursor()
cursor.execute("select temp, status from data where ID = (select MAX(ID) from data)")
# fetch all or one we'll go for all.
results = cursor.fetchall()
connection.close()

schema = {"temp": ("number", "temp"),"status": ("number", "status")}
data = results

# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(schema)
data_table.LoadData(data)
json = data_table.ToJSon(columns_order=("temp", "status"),order_by="temp")
#print results

#print "Content-type: application/json\n\n"
print "Content-type: application/json"
print

print json

当我在浏览器上打开它时,它就像一个魅力,它为我提供了我需要的 Google jsapi 的正确格式

{"rows":[{"c":[{"v":21.062},{"v":0}]}],"cols":[{"type":"number","id":"temp","label":"temp"},{"type":"number","id":"status","label":"status"}]}

下面是我的html,需要python脚本中的json数据来绘制图表

    <html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawTable);

    function drawTable() {
      var jsonData = $.ajax({
          type: "GET",
          url: "http://192.168.1.123:8099/cgi-bin/test.py",
          dataType:"json",
          async: false
          }).responseText;
          alert(jsonData);

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});
    }

    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

不幸的是,当 html 直接对 python 脚本进行 ajax 查询时,我收到了“未定义”警报。

然后我将 json 输出 1:1 复制到纯静态 html 文件,并将 ajax URL 替换为 .html 而不是动态 .py,它可以工作。

我的问题是 - 我正在尝试做的事情是否有一些限制,或者我的代码有什么问题?

我的代码基于示例 https://developers.google.com/chart/interactive/docs/php_example https://developers.google.com/chart/interactive/docs/dev/gviz_api_lib

【问题讨论】:

    标签: jquery python ajax json


    【解决方案1】:

    如果我正确阅读了您的 javascript,则 responseText 属性仅在请求完成后设置。通常,这些东西是异步执行的,所以你注册一个函数,在接收到数据后调用。例如

    function drawTable() {
      var drawChart = function(jsonData) {
          // Create our data table out of JSON data loaded from server.
          var data = new google.visualization.DataTable(jsonData);
    
          // Instantiate and draw our chart, passing in some options.
          var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
          chart.draw(data, {width: 400, height: 240});
      };
    
      $.ajax({
          type: "GET",
          url: "http://192.168.1.123:8099/cgi-bin/test.py",
          dataType:"json",
          async: false
      }).done(drawChart);
    
    }
    

    更多示例请参见jquery ajax documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多