2014-08-30 154 views
1

我正在爲使用HighCharts的時間序列數據編寫一個簡單的查看器。可能發生的一個問題是,這些值可能會停止一段時間,然後恢復。在我的系統中,這些值最終會進入數據庫,我不會丟失它們,它們只會延遲。我想在我的用戶界面上,因爲數據進來時,它每秒會正常滾動一次(如果工作正常的話)。如果數據停止,UI應該暫停滾動(這也在工作)。如果數據可用性在一段時間後恢復,那麼我希望圖表執行「填充差距」,即填充在不可用期間漏掉的部分。jQuery ajax調用返回HTML而不是JSON的Ajax響應

這就是我現在想要解決的問題。我發出同步的$ .ajax調用來獲取缺少的數據,但返回的數據是頁面本身的HTML,而不是JSON。我已經測試了服務器端調用,並且它從瀏覽器直接調用時返回JSON。所以任何人都可以看到我的「缺口填充」陰謀中出現了什麼問題?在下面的代碼中查看註釋「data2這裏是HTML而不是JSON出於某種原因」,它出錯的地方。

謝謝 維吉爾

<!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> 

+1

嘗試在您的ajaxsetup中添加'dataType:「json」'並查看是否有效 – benaich 2014-08-30 19:21:39

+0

非常好的建議,但錯誤仍然存​​在。 – user43995 2014-08-30 19:33:12

+1

您是否檢查過發送ajax請求的實際url?您的請求是否將其轉換爲服務器方法? – 2014-08-30 20:41:52

回答

0

發現問題,很基本的。我使用Python風格的sprintf格式來生成gapfill URL。我的腦海裏太多的Python了。