1

在我问的另一个问题的帮助下让我的 AJAX 工作后,我想创建另一个包含我的函数的文件,以保持我的代码干净。我没有在网上找到任何有用的东西,所以我认为这可能是不可能的。这是我要提取的代码:

<script> <!-- overall co2 -->
   var co2;
   var url="/solarpv/api/co2/list"
   var jsonObject;
   $(document).ready(function(){
       $.getJSON(url,function(result){
          jsonObject = result;
          co2 = result[0].Cumulative_CO2;
          $('#ajaxRequest').html("Our solar panels have saved " + co2 + " pounds of CO2 since they were installed.");
       });
   }); 

    <!-- today co2 -->
    var co2today;
    var url2="/solarpv/api/co2/today"
    $(document).ready(function(){
       $.getJSON(url2,function(result){
        co2today = result[0].CO2;
        $('#today').html("Our Solar Panels have saved " + co2today + " pounds of c02 so far today.");
       });
     }); 


<!-- yesterday's CO2 -->
   var url3 = "/solarpv/api/co2/list?start=2013-04-28%2001:00:00&end=2013-04-29%2001:00:00";
   var yesterdayCO2;
    $(document).ready(function(){
          $.getJSON(url3,function(result){
             yesterdayCO2 = result[0].Cumulative_CO2;
             $('#yesterday').html("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2/1.98 + " people to create!");
          });
     }); 


  <!-- last years's CO2 -->
   var url4 = "/solarpv/api/co2/list?start=2012-04-28%2001:00:00&end=2013-04-29%2001:00:00";
   var trees;
   $(document).ready(function(){
      $.getJSON(url4,function(result){
      trees = result[0].Cumulative_CO2;
      $('#yesterday').html("Last year our solar panels saved the equivalent of " + trees/48.061 + " trees worth of C02");
      });
   }); 
</script>

将留在使用它的文件中的 html 示例如下所示:

<li id="yesterday">
   <script>
      document.write("Yesterday alone, our solar panels saved the same amount of CO2 it would take " + yesterdayCO2 + " people to create!");
   </script>
</li>
4

1 回答 1

2

Use this tag to load the javascript. Put it at the bottom of your HTML just before </html>

<script type="text/javascript" src="myJs.js"></script>

Then you have to put the javascript (without the <script> tags) in the file named myJs.js and make it loadable from the browser.

于 2013-05-01T19:07:34.083 回答