首页 > 解决方案 > google.setOnLoadCallback with parameter inside jquery ajax success function

问题描述

Sample code: Both of these seem to work ok, to display a message:

google.load("visualization", "1", { packages: ["corechart"] });
...
$(document).ready(function () {

  google.setOnLoadCallback(function () {
    alert('from inside ready 1');
  });
});

$(document).ready(function () {

  google.setOnLoadCallback(alert('from inside ready 2'));
});

Note: I'm using alert(..) just for debugging purposes - my real code draws charts. Now, I want to use these techniques inside $.ajax e.g. :

  $.ajax({
    type: "POST",
    ... 
    success: function (result) {
      if (result.d) {

        $(document).ready(function () {
          alert('sucess');

          // option 1
          google.setOnLoadCallback(function () {
            alert('from inside ready 3');
          });

          // option 2
          // google.setOnLoadCallback(alert('from inside ready 4'));
        });

Now, on ajax success, I can see "sucess" shown, but option 1 doesn't seem to work. i.e. I don't see "from inside ready 3". If I enable the code at option 2, and comment out the code for option 1, I DO see "from inside ready 4".

So it seems that option 2 works, but not option 1, from a jquery ajax call. Can anyone shed some light? Is option 2 100% safe to use? It seems to work, but all the examples I've seen seem to use option 1.

标签: javascriptjquerygoogle-visualization

解决方案


首先,您使用的是旧版本的谷歌图表,
jsapi库不应再使用,
请参阅发行说明...

通过jsapi加载程序仍然可用的 Google Charts 版本不再持续更新。请从现在开始使用新的 gstatic loader.js

老的:<script src="https://www.google.com/jsapi"></script>

当前的:<script src="https://www.gstatic.com/charts/loader.js"></script>

这只会改变加载语句......

从...

google.load("visualization", "1", { packages: ["corechart"] });

至...

google.charts.load("current", { packages: ["corechart"] });

接下来,你不需要每次绘制图表时都使用回调,
只需要使用一次,以确保谷歌图表已经加载。

并且有几种使用回调的方法,
您可以使用更新的setOnLoadCallback函数。

google.charts.setOnLoadCallback(drawChart);

或者您可以将回调直接放在load语句中。

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

或者我更喜欢它返回的承诺。(谷歌为 IE 提供了一个 promise polyfill)

google.charts.load('current', {
  packages: ['corechart']
}).then(drawChart);

现在到手头的问题,
google的load声明会默认等待文件加载,
所以你可以使用google.charts.load代替$(document).ready

建议先加载 google,然后使用 ajax 获取数据,然后绘制图表。

类似于以下设置的东西...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  // get data for chart 1
  $.ajax({
    type: 'POST',
    ...
  }).done(function (result) {

    drawChart1(result.d);

  }).fail(function (jqXHR, status, errorThrown) {
    console.log(errorThrown);
  });

  // get data for chart 2
  $.ajax({
    type: 'POST',
    ...
  }).done(function (result) {

    drawChart2(result.d);

  }).fail(function (jqXHR, status, errorThrown) {
    console.log(errorThrown);
  });

});

function drawChart1(chartData) {
  ...
}

function drawChart2(chartData) {
  ...
}

推荐阅读