gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:27:32 27 4
gpt4 key购买 nike

我的页面中有 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 ...
});

但这似乎没有帮助。

<小时/>

当我刷新页面时,在网络选项卡下,我总是看到其中一个 ajax XHR GET 是红色的 (500),如下图所示。

enter image description here

<小时/>

注意:

  • 它并不总是可重现。
  • 有时,2 会返回错误。
  • 有时,不同的 GET 会返回错误。
  • 有时,所有这些 GET 都工作正常,没有错误。
<小时/>

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

我应该开始研究 JS Promise 还是 jQuery Defered 对象?

我对这些还不太了解。

<小时/>

整个代码

@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

最佳答案

听起来您可能需要顺序调用 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());

关于javascript - 防止任何 Ajax XHR GET 在页面加载时返回 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com