首页 > 解决方案 > 在ajax函数之后全局使用变量

问题描述

我遇到了一些麻烦,使变量成为全局变量,在 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
                }
            }]
        }
    }
});

标签: javascriptjqueryajaxvariables

解决方案


您的totalProfileCat变量在内部声明$ ( document ).ready()。意思是,它只会在 DOM 被加载并且它的作用域是ready()函数之后才被初始化。

ready()但是,在初始化new Chart对象时,您在函数之外使用它。因此错误。

在函数外初始化变量ready()应该没问题。


推荐阅读