防止任何Ajax XHR GET在页面加载时返回500错误

时间:2016-12-11 22:10:38

标签: javascript jquery ajax jquery-deferred

我的页面中有4个图表。

enter image description here

我只需要为4个API创建一个AJAXGET,获取数据并绘制图形。

问题:我的一个Ajax返回500错误。

我已尝试在.done()这样的

中完成所有操作
var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'});
ajax.done(function (data) {
    //do stuffs ... 
});

但这似乎没有帮助。

当我刷新页面时,在Network Tab下,我总是看到其中一个ajax XHR GET为红色(500),如下图所示。

enter image description here

注意:

  • 它不是一直可以重复的。
  • 有时候,2会返回错误。
  • 有时,不同的GET会返回错误。
  • 有时,所有这些GET都能正常工作而不会出错。

如何防止这些错误并确保所有这些GET在开始渲染之前都能正常工作?

我应该开始研究 JS promise 还是jQuery Deffered 对象?

我对这些知之甚少。

任何提示/建议/帮助都将非常感谢!

整个代码

@extends('layouts.internal.master')
@section('content')

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_0_rate"></div>
  </div>
</div>

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_hour"></div>
  </div>
</div>



<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_day"></div>
  </div>
</div>

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="graph_month"></div>
  </div>
</div>



@stop


{{-- Page-specific scripts --}}
@section('pagescripts')


<script type="text/javascript" src="/js/fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="/js/fusioncharts/fusioncharts.charts.js"></script>

<script type="text/javascript">


  //constants

  var graph_ubb_configs = {

    "subcaption": "",
    "yaxisname": "Bandwidth (KB)",
    "formatnumberscale": "1",
    "plotgradientcolor": "#0075c2",
    "palettecolors": "#03A9F4",
    "bgcolor": "FFFFFF",
    "showalternatehgridcolor": "0",
    "showplotborder": "0",
    "showvalues": "0",
    "labeldisplay": "WRAP",
    "divlinecolor": "CCCCCC",
    "suseroundedges": "1",
    "showcanvasborder": "0",
    "canvasborderalpha": "0",
    "defaultnumberscale": "KB",
    "showborder": "0",
    "captionFontSize": "14",
    "subcaptionFontSize": "14",
    "baseFont": "Roboto",
    "subcaptionFontBold": "0",
    "subcaptionFontSize": "12",
    "subcaptionFontBold": "0",
    "subcaptionFontColor": "#08c",
  };

  var t_line = [{"line": [{"startvalue": '{{ $total_bytes }}', "color": "#F44336", "valueOnRight": "1", "tooltext": "Limit", "displayvalue": "Threshold", "dashed": "1"} ] } ];

  var c_time = '{{ $hour }}';


  /*================================
  =            Zero Rate           =
  ================================*/
  // 1-31 days


  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'});
  ajax.done(function (data) {

    console.log('%c Zero Rate API ', 'background: #222; color: #bada55');
    console.log(data);

    if(data != null){

      var up_link = data.zero_rate_vlan['up_bytes']/1000000;
      var down_link = data.zero_rate_vlan['down_bytes']/1000000;


      console.log(up_link);
      console.log(down_link);




      graph_ubb_configs.caption = "Zero Rated Traffic";
      graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
      graph_ubb_configs.xaxisname = "Bandwidth";


      var gragh_ubb_0_rate = new FusionCharts({
        "type": "bar2d",
        "renderAt": "gragh_ubb_0_rate",
        "width": "100%",
        "dataFormat": "json",
        "dataSource": {
          "chart": graph_ubb_configs,
          "data":[{"label": "Uplink","value":parseFloat(up_link)}, {"label": "Downlink","value":parseFloat(down_link)}],
          "trendlines": t_line

        }
      });

      gragh_ubb_0_rate.render();

      console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

    }





  });








  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/hour'});

  ajax.done(function (data) {

    // delete data.hour_p_ubb[0];

    console.log('%c HOUR API ', 'background: #222; color: #bada55');
    console.log(data);


    var hour = [];

    for(var i=0; i<24; i++) {

      var time = i%12;

      if(time == 0){
        time = 12;
      }

      if(i<12){
        var am = 'AM';
      }else{
        var am = 'PM';
      }

      var val = data.hour_p_ubb[i]['up_bytes']/1000000 + data.hour_p_ubb[i]['down_bytes']/1000000;
      var object = {"label":time + ' ' + am,"value": + val};
      hour[i] = object;

    }

    console.log('%c HOUR Value ', 'background: #222; color: #bada55');
    console.log(JSON.stringify(hour));

    graph_ubb_configs.caption = "Daily Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y + ' ( '+data.time+' )';
    graph_ubb_configs.xaxisname = "Hours of Day";

    var gragh_ubb_hour = new FusionCharts({
      "type": "column2d",
      "renderAt": "gragh_ubb_hour",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "data":hour,
        // "trendlines": t_line

      }
    });


    gragh_ubb_hour.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

  });



  /*=============================
  =            DAY            =
  =============================*/
  // 1-31 days


  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/day'});
  ajax.done(function (data) {

    console.log('%c DAY API ', 'background: #222; color: #bada55');
    console.log(data);

    // var day = [];
    var labels = [];
    var values = [];

    for(var i=0; i<data.day_p_ubb.length; i++) {

      var up_link = parseFloat(data.day_p_ubb[i]['up_bytes'])/1000000;
      var down_link = parseFloat(data.day_p_ubb[i]['down_bytes'])/1000000;
      var val = parseFloat(up_link+down_link);
      var c_d = data.d;

      if(i == 0){
        var c_val = 0;
      }else{

        if(i <= c_d ){
          var c_val = parseFloat(c_val) + parseFloat(val);
        }else{
          var c_val = '';
        }

      }

      var label_object = {"label":String(i+1)};
      var data_object = {"value":parseFloat(c_val)};

      labels[i] = label_object;
      values[i] = data_object;

    }

    graph_ubb_configs.caption = "Monthly Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
    graph_ubb_configs.xaxisname = "Days of Month";


    var gragh_ubb_day = new FusionCharts({
      "type": "msline",
      "renderAt": "gragh_ubb_day",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "categories": [{"category": labels } ], "dataset": [{"data": values } ],
        "trendlines": t_line

      }
    });

    gragh_ubb_day.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');


  });







  /*============================
  =            Month           =
  ============================*/

  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/month'});
  ajax.done(function (data) {

    console.log('%c MONTH API ', 'background: #222; color: #bada55');
    console.log(data);

    var month = [];
    for(var i=0; i<12; i++) {

      var val = data.month_p_ubb[i]['up_bytes']/1000000 + data.month_p_ubb[i]['down_bytes']/1000000;

      if(i == 0){
        var object = {"label":'January',"value": val};
      }else if(i == 1){
        var object = {"label":'Febuary',"value": val};
      }else if(i == 2){
        var object = {"label":'March',"value": val};
      }else if(i == 3){
        var object = {"label":'April',"value": val};
      }else if(i == 4){
        var object = {"label":'May',"value": val};
      }else if(i == 5){
        var object = {"label":'June',"value": val};
      }else if(i == 6){
        var object = {"label":'July',"value": val};
      }else if(i == 7){
        var object = {"label":'August',"value": val};
      }else if(i == 8){
        var object = {"label":'September',"value": val};
      }else if(i == 9){
        var object = {"label":'October',"value": val};
      }else if(i == 10){
        var object = {"label":'November',"value": val};
      }else{
        var object = {"label":'December',"value": val};
      }

      month[i] = object;
    }

    console.log('%c Month Value', 'background: #222; color: #bada55');
    console.log(JSON.stringify(month));


    graph_ubb_configs.caption = "Yearly Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
    graph_ubb_configs.xaxisname = "Months of Year";


    var graph_month = new FusionCharts({
      "type": "column2d",
      "renderAt": "graph_month",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "data":month,
        "trendlines": t_line
      }
    });

    graph_month.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

  });

</script>


@stop

1 个答案:

答案 0 :(得分:1)

听起来你可能需要按顺序而不是并行地进行ajax调用。

首先,将您的四个部分包裹在function() {...}中并从每个部分返回jqXHR

function make_zero_rate_graph() {
    /*================================
    =            Zero Rate           =
    ==================================*/
    // 1-31 days
    return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'}).then(function(data) {
        if(data) {
            var gragh_ubb_0_rate = new FusionCharts({
                'type': 'bar2d',
                'renderAt': 'gragh_ubb_0_rate',
                'width': '100%',
                'dataFormat': 'json',
                'dataSource': {
                    'chart': $.extend({}, graph_ubb_configs, {
                        'caption': 'Zero Rated Traffic',
                        'subcaption': [data.m, data.d, data.y].join('/'),
                        'xaxisname': 'Bandwidth'
                    }),
                    'data': [
                        { 'label': 'Uplink', 'value': +data.zero_rate_vlan.up_bytes / 1000000 }, 
                        { 'label': 'Downlink', 'value': +data.zero_rate_vlan.down_bytes / 1000000 }
                    ],
                    'trendlines': t_line
                }
            });
            gragh_ubb_0_rate.render();
        }
    });
}

function make_hour_graph() {
    /*===========================
    =            Hour           =
    =============================*/
    return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/hour'}).then(function(data) {
        var gragh_ubb_hour = new FusionCharts({
            'type': 'column2d',
            'renderAt': 'gragh_ubb_hour',
            'width': '100%',
            'dataFormat': 'json',
            'dataSource': {
                'chart': $.extend({}, graph_ubb_configs, {
                    'caption': 'Daily Network Usage',
                    'subcaption': data.m + '/' + data.d + '/' + data.y + ' ( '+data.time+' )',
                    'xaxisname': 'Hours of Day'
                }),
                'data': data.hour_p_ubb.slice(0, 24).map(function(item, i) {
                    return {
                        'label': (i%12 || 12) + ' ' + ((i<12)?'AM':'PM'),
                        'value': (+item.up_bytes + +item.down_bytes) / 1000000
                    });
                }),
                // 'trendlines': t_line
            }
        });
        gragh_ubb_hour.render();
    });
}

function make_day_graph() {
    /*===========================
    =            DAY            =
    =============================*/
    // 1-31 days
    return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/day'}).then(function (data) {
        var c_val = 0;
        var gragh_ubb_day = new FusionCharts({
            'type': 'msline',
            'renderAt': 'gragh_ubb_day',
            'width': '100%',
            'dataFormat': 'json',
            'dataSource': {
                'chart': $.extend({}, graph_ubb_configs, {
                    'caption': 'Monthly Network Usage',
                    'subcaption': data.m + '/' + data.d + '/' + data.y,
                    'xaxisname': 'Days of Month'
                }),
                'categories': [{
                    'category': data.day_p_ubb.map(function(_, i) {
                        return { 'label': String(i+1) };
                    })
                }],
                'dataset': [{
                    'data': data.day_p_ubb.map(function(item, i) {
                        c_val += (i > 0 && i <= data.d) ? ((+item.up_bytes + +item.down_bytes) / 1000000) : 0;
                        return { 'value': c_val };
                    })
                }],
                'trendlines': t_line
            }
        });
        gragh_ubb_day.render();
    });
}

function make_month_graph() {
    /*============================
    =            Month           =
    ==============================*/
    var months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November','December'];
    return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/month'}).then(function (data) {
        var graph_month = new FusionCharts({
            'type': 'column2d',
            'renderAt': 'graph_month',
            'width': '100%',
            'dataFormat': 'json',
            'dataSource': {
                'chart': $.extend({}, graph_ubb_configs, {
                    'caption': 'Yearly Network Usage',
                    'subcaption': [data.m, data.d, data.y].join('/'),
                    'xaxisname': 'Months of Year'
                }),
                'data': data.month_p_ubb.slice(0,12).map(function(data, i) {
                    return {
                        'label': months[i],
                        'value': (+data.up_bytes + +data.down_bytes) / 1000000
                    };
                }),
                'trendlines': t_line
            }
        });
        graph_month.render();
    });
}

功能中的代码已整理但未经过测试

有了这些功能,按顺序调用是微不足道的:

// List the functions in an array 
var fns = [ make_zero_rate_graph, make_hour_graph, make_day_graph, make_month_graph ];

// And build a then() chain by reducing the array,
// see http://stackoverflow.com/documentation/javascript/231/promises/5917/#t=201612121359154320486
fns.reduce(function(jqPromise, fn) {
    return jqPromise.then(fn);
}, $.when());