2015-11-11 125 views
1

我們使用AJAX來顯示用戶的統計信息 - 每月(當前月份和前12個月)發送和接收的郵件數量。我正在使用Google圖表。當我沒有使用AJAX的時候,它可以工作,但使用AJAX Google圖表不起作用 - 整個頁面變成空白,控制檯中也沒有例外。這裏是我的代碼:谷歌圖表不能正常工作

<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     var params = { 
      "email": "{{ statistics_user_email }}", 
      "today_email_statistics_query_job_json": JSON.stringify({{ today_email_statistics_query_job_json|safe }}), 
      "this_month_email_statistics_query_job_json": JSON.stringify({{ this_month_email_statistics_query_job_json|safe }}), 
      "last_13_months_monthly_email_statistics_query_job_json": JSON.stringify({{ last_13_months_monthly_email_statistics_query_job_json|safe }}) 
     }; 

     function try_ajax() { 
      $.ajax({ 
       type: 'POST', 
       url: '/ajax/user/email_statistics', 
       data: params, 
       success: function(reply) { 
        if (reply.wait === true) { 
         // Try again after 4 seconds. 
         setTimeout(try_ajax, 4000); 
        } else if (reply.ready === true) { 
         function drawTitleSubtitle() { 
          var data = new google.visualization.DataTable(); 
          data.addColumn('string', 'Month'); 
          data.addColumn('number', 'Emails sent'); 
          data.addColumn('number', 'Emails received'); 

          var rows = []; 
          for (var i = 0; i < reply["last_13_months_monthly_email_statistics"].length; i++) { 
           var row = reply["last_13_months_monthly_email_statistics"][i]; 
           rows.push([row["month"], row["sent"], row["received"]]); 
          } 
          data.addRows(rows); 

          var options = { 
           'title': 'How Many Vegan Cheeseburgers I Ate Last Night', 
           'width': 400, 
           'height': 300 
          }; 

          var material = new google.charts.Bar(document.getElementById('last-13-month-chart-div')); 
          material.draw(data, options); 
         } 

         $("#today-emails-sent-span").html(reply["today_email_statistics"]["messages_sent"]); 
         $("#today-emails-received-span").html(reply["today_email_statistics"]["messages_received"]); 
         $("#this-month-emails-sent-span").html(reply["this_month_email_statistics"]["messages_sent"]); 
         $("#this-month-emails-received-span").html(reply["this_month_email_statistics"]["messages_received"]); 
         google.load('visualization', '1', {packages: ['corechart', 'bar']}); 
         google.setOnLoadCallback(drawTitleSubtitle); 
         $("#please-wait-div").addClass("hidden"); 
         $("#email-statistics-div").removeClass("hidden"); 
        } else { 
         console.error("AJAX returned unexpected results!", reply); 
        } 
       } 
      }); 
     } 

     try_ajax(); 
    }); 
</script> 

當我評論以下行,它的工作原理沒有圖表:

     google.load('visualization', '1', {packages: ['corechart', 'bar']}); 
         google.setOnLoadCallback(drawTitleSubtitle); 

的AJAX返回此對象一次:

{"wait": true} 

了第二遍:

{"ready": true, "last_13_months_monthly_email_statistics": [{"received": 23, "sent": 2, "month": "2015-10"}, {"received": 15, "sent": 4, "month": "2015-11"}], "this_month_email_statistics": {"messages_received": 15, "messages_sent": 4}, "today_email_statistics": {"messages_received": 0, "messages_sent": 1}} 

我是不包括HTML,但頁面上存在所有元素。除了圖表之外的所有東西都可以工作,在我沒有使用AJAX的時候,這個工作方式很有用。問題是什麼?

順便說一句,我只加載了本月和上個月的數據,這不是一個錯誤。未來我們可以顯示前12個月。

我試圖在功能drawTitleSubtitle()中使用console.log,但它似乎根本沒有被調用。但在AJAX返回結果(第二次調用結果)後<html>內部沒有<body>

JS小提琴 - http://jsfiddle.net/uriwise/Lpsb0tqn/

+1

也許谷歌不喜歡的素食乾酪牛肉三明治這是:) –

+2

@ T3H40比薩餅(從https://google-developers.appspot.com/chart複製/ interactive/docs/quick_start),我改變了它::-) – Uri

+1

你走了!問題解決,修復和關閉。 –

回答

1

你看到的行爲(「drawTitleSubtitle() [...]似乎並沒有被稱爲」)主要是由於操作的執行順序。

因爲你加載所需的軟件包(google.load(...))和內$(document).ready()設置所需的回調(google.setOnLoadCallback(...)),谷歌的API圖表無法引用所需的回調(drawTitleSubtitle())時,最終被裝入包。

您應該定義drawTitleSubtitle(),加載所需的包(google.load(...))並在輸入$(document).ready()之前設置所需的回調google.setOnLoadCallback(...)

$(document).ready()之內,try_ajax()應當調用drawTitleSubtitle(),同時傳遞來自/ajax/user/email_statistics的期望的Ajax響應。

0

最終我做了Lee建議的功能,並且在不等待$(document).ready()的情況下調用google函數。這裏是我的代碼:

編輯:我把我的代碼分成3個獨立的函數,並在調用它們時傳遞參數。

<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script type="text/javascript"> 
    function draw_google_chart(ajax_reply) { 
     var data = new google.visualization.DataTable(); 
     data.addColumn('string', 'Month'); 
     data.addColumn('number', 'Emails sent'); 
     data.addColumn('number', 'Emails received'); 

     var rows = []; 
     for (var i = 0; i < ajax_reply["last_13_months_monthly_email_statistics"].length; i++) { 
      var row = ajax_reply["last_13_months_monthly_email_statistics"][i]; 
      rows.push([row["month"], row["sent"], row["received"]]); 
     } 
     data.addRows(rows); 

     var options = { 
      'title': 'How Many Vegan Cheeseburgers I Ate Last Night', 
      'width': 400, 
      'height': 300 
     }; 

     var material = new google.charts.Bar(document.getElementById('last-13-month-chart-div')); 
     material.draw(data, options); 
    } 

    function try_ajax(ajax_params) { 
     $.ajax({ 
      type: 'POST', 
      url: '/ajax/user/email_statistics', 
      data: ajax_params, 
      success: function(ajax_reply) { 
       if (ajax_reply.wait === true) { 
        // Try again after 4 seconds. 
        setTimeout(function() { 
         try_ajax(ajax_params); 
        }, 4000); 
       } else if (ajax_reply.ready === true) { 
        $("#today-emails-sent-span").html(ajax_reply["today_email_statistics"]["messages_sent"]); 
        $("#today-emails-received-span").html(ajax_reply["today_email_statistics"]["messages_received"]); 
        $("#this-month-emails-sent-span").html(ajax_reply["this_month_email_statistics"]["messages_sent"]); 
        $("#this-month-emails-received-span").html(ajax_reply["this_month_email_statistics"]["messages_received"]); 
        draw_google_chart(ajax_reply); 
        $("#please-wait-div").addClass("hidden"); 
        $("#email-statistics-div").removeClass("hidden"); 
       } else { 
        console.error("AJAX returned unexpected results!", ajax_reply); 
       } 
      } 
     }); 
    } 

    function try_ajax_first_time() { 
     $(document).ready(function() { 
      var ajax_params = { 
       "email": "{{ statistics_user_email }}", 
       "today_email_statistics_query_job_json": JSON.stringify({{ today_email_statistics_query_job_json|safe }}), 
       "this_month_email_statistics_query_job_json": JSON.stringify({{ this_month_email_statistics_query_job_json|safe }}), 
       "last_13_months_monthly_email_statistics_query_job_json": JSON.stringify({{ last_13_months_monthly_email_statistics_query_job_json|safe }}) 
      }; 

      try_ajax(ajax_params); 
     }); 
    } 

    google.load('visualization', '1', {packages: ['corechart', 'bar']}); 
    google.setOnLoadCallback(try_ajax_first_time); 
</script> 

請注意,功能try_ajaxdraw_google_chart$(document).ready()後總是叫,從來沒有(因爲我需要的HTML元素是在DOM)。

JS小提琴 - http://jsfiddle.net/uriwise/tp1xhun0/

但是,如果我叫內$(document).ready()google功能,然後它不工作,我再次得到了空白頁。我沒有找到這個文件對谷歌的網站:

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