使用Google Charts绘制折线图时遭遇Container not defined异常求助
Hey there, let's break down why you're hitting this error and fix it step by step:
Root Cause of the Error
The biggest issue here is the document.write() calls scattered in your code. When document.write() runs after the page has finished loading (which happens when the Google Charts callback fires), it completely rewrites the entire HTML document. This deletes the <div id="curve_chart"></div> container your chart needs to render into—hence the "Container is not defined" error.
There's also a small tweak needed for how you handle the JSON data from your request attribute to avoid unexpected behavior.
Step-by-Step Fixes
1. Remove All document.write() Statements
Replace them with console.log() for debugging. document.write() is almost never the right choice for post-load content, as it wipes out existing page elements.
2. Correctly Handle the JSON Data
Your current code uses var newstring = <%= request.getAttribute("json_string")%> followed by JSON.parse(newstring). If your backend passes a properly formatted raw JSON array (like your example), you can skip the JSON.parse() by directly assigning the output to your variable (since JSP will render it as a valid JavaScript object array). If your backend returns a quoted string (e.g., '[{"f1":414,...}]'), wrap the attribute output in quotes before parsing.
3. Ensure DOM Execution Order
Place your chart container div before the chart-related scripts. This guarantees the container exists in the DOM when Google Charts tries to render into it.
Modified Working Code
<body> <!-- header --> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#">Dashboard</a> </div> </div> </nav> <!-- header --> <h1>welcome</h1> <!-- Chart container - placed above chart scripts to ensure it exists when needed --> <div id="curve_chart"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Simplified JSON data handling (adjust if your backend returns a quoted string) var chartData = <%= request.getAttribute("json_string")%>; // Use this line instead if your backend returns a quoted JSON string: // var chartData = JSON.parse('<%= request.getAttribute("json_string")%>'); // Debug with console.log instead of document.write console.log("Received chart data:", chartData); for(let i=0;i<chartData.length;i++) { const currentObj = chartData[i]; console.log(`f1: ${currentObj.f1}, Timestamp: ${currentObj.ts}`); } // Load Google Charts and set render callback google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { const dTable = new google.visualization.DataTable(); dTable.addColumn('string','timestamp'); dTable.addColumn('number','f1'); for(let i=0;i<chartData.length;i++) { console.log("Adding row to data table..."); const currentObj1 = chartData[i]; dTable.addRow([currentObj1.ts, currentObj1.f1]); } const options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' } }; // The container now definitely exists in the DOM const chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(dTable, options); } </script> </body>
Key Takeaways
- The
curve_chartdiv is positioned before chart scripts to ensure it's available whendrawChart()runs. console.log()provides safe debugging without breaking the page structure.- JSON handling is adjusted to match common backend output formats, eliminating parsing errors.
内容的提问来源于stack exchange,提问作者Nikhil

