简体   繁体   中英

JQuery.load() page containingJavaScript

I have a html page which contains the some javascript to generate a chart from Google API. WHen I access the page directly, it works as expected, showing the chart.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
   //// code to generate chart
   var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
   chart.draw(data, options);
}
</script>
<div id="chart_div">
   Chart Div
</div>

I want to load this chart into a on another page. I tried using JQuery's $.get and $.load, but neither are working. IF I add some text to the page and call get/load i can see the text but not the chart - it seems the Javascript is not executing.

I added alert('msg') and saw that the google.load got called, but no other JS was being called.

From the other page where I want include the chart I have the following JS:

$(document).ready(function () {
    $('#test').load('chart?param=1', function () {
        alert('Load was performed.');
    });
});

but the 'load was performed' never gets hit.

"SCRIPT5009: 'google' is undefined"

I suspect that this <script type="text/javascript" src="https://www.google.com/jsapi"></script> isn't working when you .load() that block of code. Since jQuery is already running try this

<!-- get rid of this <script type="text/javascript" src="https://www.google.com/jsapi" -->
<script type="text/javascript">
// does not need $(function()) unless you're running this on its own
// when loading this in using $.load() it's already ready.

$.getScript('https://www.google.com/jsapi', function(){
    google.load('visualization', '1.0', { 'packages': ['corechart'] });
    google.setOnLoadCallback(drawChart);
});
function drawChart() {
   //// code to generate chart
   var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
   chart.draw(data, options);
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM