ajax json直接查询到python生成的html获取未定义

我现在已经挣扎了三个星期,我已经走到了尽头。 系统管理员是开发人员:)

我正在尝试构建轻量级的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数据来绘制图表

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

不幸的是,当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

如果我正确读取您的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文档中找到更多示例。