js处理json数据问题
问题
利用js动态处理json数据,图表实时显示增量数据,代码之前测试可以正常显示,现在又不可以了,求指点
代码
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Data</title>
<script src="/static/jquery-1.8.3.min.js"></script>
<script src="/static/highstock.js"></script>
</head>
<body>
<div id="container" style="min-width:400px;height:400px"></div>
<script>
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
},
credits: {
enabled: false
},
legend: {
enabled: true
}
});
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['user','system'];
/**
* Create the chart when all data is loaded
* @returns {undefined}
*/
function createChart() {
$('#container').highcharts('StockChart', {
chart:{
events:{
load:function () {
var ser = [];
for(var i=0;i<names.length;i++){
ser[i]=this.series[i];
}
setInterval(function () {
$.each(names,function (j,name) {
$.getJSON('/api/data?q='+name.toLowerCase(),function (res) {
$.each(res,function (i,v) {
ser[j].addPoint(v)
})
})
})
},5000)//5s checkout
}
}
},
rangeSelector: {
selected: 0
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions
});
}
$.each(names, function (i, name) {
$.getJSON('/api/data?q=' + name.toLowerCase(), function (data) {
seriesOptions[i] = {
name: name,
data: data
};
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
});
</script>
</body>
</html>
是不是5s刷新一次写错了?
#!/usr/bin/env python# coding=utf-8
from flask import Flask,render_template,request
from mod import app,db,Cpu
import json
cx_time = 0
@app.route('/')
def index():
cpu = Cpu.query.all()
return render_template('index.html',cpu=cpu)
@app.route('/api/<name>')
def api(name):
if name=='data':
q=request.args['q']
global cx_time
if cx_time > 0:
qname = Cpu.query.filter(Cpu.time > cx_time / 1000).all()
else:
qname = Cpu.query.all()
arr = []
for i in qname:
if q=='user':
arr.append([i.time*1000,i.user])
elif q=='system':
arr.append([i.time*1000,i.system])
elif q=='idle':
arr.append([i.time*1000,i.idle])
if len(arr)>0:
cx_time=arr[-1][0]
#cx_time=0
#cx_time=0
return json.dumps(arr)
@app.route('/data')
def data():
global cx_time
if cx_time > 0:
cpu = Cpu.query.filter(Cpu.time > cx_time/1000 ).all()
else:
cpu = Cpu.query.all()
arr = []
for i in cpu:
arr.append([i.time*1000,i.user])
if len(arr)>0:
cx_time =arr[-1][0]
return json.dumps(arr)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000,debug=True)
#!/usr/bin/env python# coding=utf-8
from flask import Flask,render_template
from flask_sqlalchemy import SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
class Cpu(db.Model):
user = db.Column(db.Float,primary_key=True)
system = db.Column(db.Float)
idle = db.Column(db.Float)
time = db.Column(db.Integer)
def __init__(self,user,system,idle,time):
self.user = user
self.system = system
self.idle = idle
self.time = time
def __repr__(self):
return '{0} {1}'.format(self.user,self.time)
#!/usr/bin/env python# coding=utf-8
import time
import psutil
from mod import db,Cpu
db.create_all()
def getCpu():
info = psutil.cpu_times()
data = []
data.append(info.user)
data.append(info.system)
data.append(info.idle)
cpu=Cpu(user=data[0],system=data[1],idle=data[2],time=int(time.time()))
db.session.add(cpu)
db.session.commit()
while True:
time.sleep(5)
getCpu()
代码如上,之前测试还可以的
回答:
个人测过没有报错,请问楼主,现在又不可以了是什么意思?
以上是 js处理json数据问题 的全部内容, 来源链接: utcz.com/a/162150.html