在将变量全局化为ajax函数中声明的值可以在其他函数中使用的位置时遇到了一些麻烦。我认为通过在函数外部定义变量,可以在函数中重新定义变量时重写其值,并可以在其他地方使用。
现在,我的图表函数出现一个错误,提示未定义totalProfileCat
。
如何使我的变量成为全局变量,以便在ajax函数中定义变量后可以在多个函数中使用它们?
<div id="totalProfileViews"></div>
JS-我在哪里定义变量
//Totals
var totalProfileCat = 0; //Total Profile Catalogs
function ajaxCallCatalogs() {
$.ajax({
url: 'php/catalogSelect.php',
datatype: 'json',
success: function (data) {
//console.log(data);
obj = JSON.parse(data);
totalProfileCat = obj.totalProfile; //Total Profile
}
});
}
ajaxCallCatalogs();
setInterval(ajaxCallCatalogs, 150000); //1 min call 60000
console.log('value start now' + parseInt(totalCatalogs));
JS-我尝试在ajax函数之后调用修改后的变量的地方:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Profile Catalog', 'Blue'],
datasets: [{
label: '# of Votes',
data: [totalProfileCat, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
更新2-完整JS
var totalProfileCat = 0; //Total Profile Catalogs
$(document).ready(function() {
$('.arrow').click(function() {
var i = $(this).closest('.subViewBox').find('.subViewBoxExpand'),
t = $(this).addClass('active');
i.slideToggle(500).find('.subViewBoxExpand').animate({
opacity: 1
}, 1500) + t, $('.subViewBoxExpand').not(i).slideUp(800).prev().removeClass('active');
//$('.subViewBoxExpand').toggleClass('active');
});
//Totals
var totalCatalogs = 0; //Total Catalogs
var totalFastCat = 0; //Total Fastening Tech Catalogs
//Total Popular
var totalProfilePop = 0;
var totalFastPop = 0;
//Total Product Specific
var totalProfileSpec = 0;
var totalFastSpec = 0;
function ajaxCallCatalogs() {
$.ajax({
url: 'php/catalogSelect.php',
datatype: 'json',
success: function (data) {
//console.log(data);
obj = JSON.parse(data);
totalCatalogs = obj.totalCount; //Total Catalogs
totalProfileCat = obj.totalProfile; //Total Profile Catalogs
totalFastCat = obj.totalFastTech; //Total Fastening Tech Catalogs
//Total Popular
totalProfilePop = obj.totalProfilePopular;
totalFastPop = obj.totalFastTechPopular;
//Total Product Specific
totalProfileSpec = obj.totalProfileProdSpec;
totalFastSpec = obj.totalFastTechProdSpec;
$('#totalCatalogViews').html(totalCatalogs);
$('#totalProfileViews').html(totalProfileCat);
$('#totalProfilePopViews').html(totalProfilePop);
$('#totalProfileProdViews').html(totalProfileSpec);
$('#totalFastViews').html(totalFastCat);
$('#totalFastTechPopViews').html(totalFastPop);
$('#totalFastTechProdViews').html(totalFastSpec);
//myChart.settings.data = [ { value: parseInt(totalCatalogs), color: { normal: '#00f', active: '#3b4fdb', } }, { value: parseInt(totalProfileCat), color: { normal: '#b82222', active: '#d53f00' } }, { value: parseInt(totalFastCat), color: { normal: '#51e466', active: '#59ff70' } } ];
myChart.settings.data[0].value = parseInt(totalCatalogs); myChart.settings.data[1].value = parseInt(totalProfileCat); myChart.settings.data[2].value = parseInt(totalFastCat);
//myChart._methods.Update(myChart);
myChart._methods.Refresh(myChart);
}
});
}
ajaxCallCatalogs();
setInterval(ajaxCallCatalogs, 150000); //1 min call 60000
console.log('value start now' + parseInt(totalCatalogs));
console.log('value start now for profile ' + parseInt(totalProfileCat));
//Donut Chart
const myChart = $("#element").jChart({
// selectors
elements: {
container: null,
body: null,
group: null,
figure: null,
svg: null,
segments: [],
markers: null
},
// your own data
data: [
{
value: totalCatalogs,
color: { normal: '#00f', active: '#3b4fdb', },
draw: true,
push: true
},
{
value: totalProfileCat,
color: { normal: '#b82222', active: '#d53f00' },
draw: true,
push: true
},
{
value: totalFastCat,
color: { normal: '#51e466', active: '#59ff70' },
draw: true,
push: true
}
],
// values necessary for the graphing, like sum of values of all segments
values: {},
placeholder: {
data: {
value: 0, // value of the segment
color: {
normal: '#00a3f2', // stroke/fill color of the segment
active: '#00d8f2',
},
draw: true, // whether to draw the segment on the chart or not; default true
push: true, // whether to push the next segment via offset. Best to set false together when draw is set to false (the empty section will always be at the end that way); default true
order: null, // drawing order
title: '',
strokeWidth: 3
}
},
// appearance options
appearance: {
type: 'donut', // or 'pie', 'bar'
subType: 'path',
baseColor: '#ddd',
segmentColor: {
normal: '#00a3f2',
active: '#00d8f2',
},
baseOffset: 0, // offset for starting point of first segment
baseStrokeWidth: 1,
strokeWidth: 3, // default stroke width for all segments
animated: true,
title: {
chartTitle: '',
showValue: true, // tooltips
showPercentage: true,
showSummary: true, // summary - show a value inside the donut chart
summaryTitle: parseInt(totalCatalogs), // by default it shows the percentage of the greatest segment in the chart
// (if summaryTitle is empty)
summarySegment: null // the segment's id which percentage will be displayed in the summary
},
/* DONUT AND CIRCLE */
radius: 100 / (2 * Math.PI),
innerCutout: 0.75, // how "thin" the segments are from the center point. (0 will render a pie chart (full circle))
centerX: 21,
centerY: 21,
/* DONUT */
//subType: 'circle', // render type: circle for circle based approach, path for line and arc approach using path
isGauge: false, // if the donut will be rendered as a full circle or a half-circle
gap: 0, // gap between segments for donut chart (in percentage, 1 = 1%)
},
// callback function
callbacks: {
onInit() {
},
onRefresh() {
},
onSegmentMouseover() {
},
onSegmentMouseout() {
}
}
});
});
//chart.js
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Profile Catalog', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [totalProfileCat, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
答案 0 :(得分:0)
您的totalProfileCat
变量在$ ( document ).ready()
内部声明。这意味着,只有在加载DOM之后,它才会被初始化,并且其范围是ready()
函数。
但是,在初始化ready()
对象时,可以在new Chart
函数外部使用它。因此是错误。
在ready()
函数外部初始化变量,应该没问题。