如何将JSON数组数据从一个JS函数发送到另一个

How to send JSON array data from one JS function to Another?

本文关键字:JS 一个 函数 另一个 JSON 数组 数据      更新时间:2023-09-26

我正在从另一个调用JS函数并发送JSON数组数据。在将数据发送到第二个函数时,我得到的值为undefined/null。如何将JSON数组数据从一个JS函数发送到另一个JS功能?

功能:1

$(function createJsonArray() {
            var categories =  [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ];
            var confidence = [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];
            var jsonArray = {
                issueData: []
            };
            jsonArray.issueData.push({
                "categories": categories,
                "confidence": confidence
            });
            //alert('categories: ' + jsonArray.issueData[0].categories);

            // calling function-2
            createGraph(JSON.stringify(jsonArray));
        });

功能:2

$(function createGraph(graphData) {
            var jsonArray = $.parseJSON(graphData);
            alert('jsonArray: ' + jsonArray);
            $('#container').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: 'Monthly Average Rainfall'
                },
                subtitle: {
                    text: 'Source: WorldClimate.com'
                },
                xAxis: {
                    categories: jsonArray.issueData[0].categories,
                    crosshair: true
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'Rainfall (mm)'
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                        '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    useHTML: true
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: [{
                    name: 'Tokyo',
                    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
                }]
            });
        });

JSfiddle链接

检查此更新fiddle

您需要调用createJSONArray()方法并去掉$(function functionName)的jquery调用,而只需定义一个简单的方法。