简体   繁体   中英

jQuery ajax call inside ajax response returning HTML rather than JSON

I am writing a simple viewer for time series data using HighCharts. One problem that can happen is that the values can stop coming in for a period, then resume. On my system those values do eventually make it into the database, I do not lose them, they are just delayed. What I want on my UI is for it to scroll normally once per second as data is coming in (this if working fine). If data stops, the UI should pause scrolling (this is also working). If data availability resumes some time later, then I'd like the chart to do a "gap fill", ie populate the parts that it missed during the unavailable period.

That's what I'm trying to fix now. I issue a synchronous $.ajax call to get the missing data, but the data returned is the HTML of the page itself, not JSON. I've tested the server side call and it is returning JSON fine when called from a directly from a browser. So can anyone see what is going wrong in my "gap fill" plotting? See comment "data2 here is HTML not JSON for some reason" in the code below for where it's going wrong.

Thank you, Virgil

 <!doctype html> <html lang="en"> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <script> function log(msg) { if ( window.console && window.console.log ) { console.log(msg) } } function pauseBtnHandler() { pauseChart = !pauseChart if (pauseChart) { $('#pauseBtn').val('Resume Display') } else { $('#pauseBtn').val('Pause Display') } } function timestampToLocaldate(timestamp) { return new Date(timestamp - TIMEZONE_OFFSET) } $(function () { $(document).ready(function() { $.ajaxSetup({ cache: false }) pauseChart = false prevTimestamp = 0 prevScroll = true dataStoppedTimestamp = false // get localtime offset in minutes, then convert to ms for use with charting offset = new Date().getTimezoneOffset() TIMEZONE_OFFSET = -offset * 60 * 1000 SAMPLE_PERIOD = 1000 // Do an initial query to get the current latest timestamp (in ms since Epoch) jQuery.ajax({ url: '/mgmt/currentValues', success: function(data) { now = data['timestamp'] * 1000 + TIMEZONE_OFFSET }, error: function (xhr, ajaxOptions, thrownError) { alert('Error getting initial timestamp, defaulting time to now ' + thrownError) now = new Date().getTime() }, async: false }); var chart; $('#chart').highcharts({ chart: { type: 'spline', animation: Highcharts.svg, // don't animate in old IE backgroundColor: { linearGradient: [0, 0, 0, 500], stops: [ [0, 'rgb(160, 160, 160)'], [1, 'rgb(0, 0, 0)'] ] }, events: { load: function() { var series1 = this.series[0]; setInterval(function() { $.get("mgmt/currentValues",function(data, status){ if (!pauseChart) { var timestamp = data['timestamp'] * 1000 + TIMEZONE_OFFSET // Only scroll the chart if a more recent value has come in dt = timestamp - prevTimestamp var scroll = (dt > 0) if (!scroll) { dataStoppedTimestamp = timestamp } // Determine if gap fill required if (prevScroll == false && scroll == true && dt > SAMPLE_PERIOD) { log('doing gapfill from ' + timestampToLocaldate(dataStoppedTimestamp) + ' to ' + timestampToLocaldate(timestamp)) jQuery.ajax({ url:'/mgmt/getdatafortimeperiod/%d/%d' % (dataStoppedTimestamp, timestamp), success: function(data2) { // data2 here is HTML not JSON for some reason log(data2) for (row2 in data2) { var timestampGf = row2['timestamp'] * 1000 + TIMEZONE_OFFSET series1.addPoint([timestampGf, row2['cpuPct']], false, true) } }, error: function (xhr, ajaxOptions, thrownError) { alert('Error getting gapfill data ' + thownError) }, async: false }); } series1.addPoint([timestamp, data['cpuPct']], scroll, true) log(timestampToLocaldate(timestamp) + ' ' + data['cpuPct']) prevTimestamp = timestamp prevScroll = scroll } }); }, SAMPLE_PERIOD); } } }, title: { text: 'PERFORMANCE DATA', style: { color: 'black', fontWeight: 'bold', fontSize: '1.5em', fontFamily: 'Arial', } }, xAxis: { type: 'datetime', tickPixelInterval: 150, labels: { style: { color: 'white', fontFamily: 'Arial', }, } }, yAxis: [{ lineWidth: 1, min: 0, labels: { style: { color: 'white', fontFamily: 'Arial', }, }, title: { text: 'CPU (%)', style: { color: 'white', fontWeight: 'bold', fontSize: '16px', fontFamily: 'Arial', } } }], tooltip: { formatter: function() { str = '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+ Highcharts.numberFormat(this.y, 0); return str; } }, legend: { enabled: true, itemStyle: { color: 'white', font: 20, }, backgroundColor: '#1C1C1C', margin: 30, itemDistance: 22, symbolWidth:22, symbolHeight:16, }, exporting: { enabled: true }, series: [{ name: 'CPU %', color: '#FF0000', data: (function() { // generate an initial array of data var data = [], time = now, i; for (i = -39; i <= 0; i++) { data.push({ x: time + i * SAMPLE_PERIOD, y: 0 }); } return data; })() }, ] }); }); }); </script> </head> <body> <div id="graph"> <div id="chart" style="; height: 100%; margin: 0 auto; "></div> <div id="pauseButton"> <input id="pauseBtn" type="submit" value="Pause Display" onclick="pauseBtnHandler();"> </div> </div> </body> </html> 

Found the problem, pretty basic. I was using Python style sprintf formatting to generate the gapfill URL. Too much Python on my mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM