从文件中提取AJAX

时间:2013-05-01 19:04:15

标签: javascript html ajax

让我的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>

1 个答案:

答案 0 :(得分:2)

使用此标记加载javascript。在</html>

之前将其放在HTML的底部
<script type="text/javascript" src="myJs.js"></script>

然后你必须将javascript(没有<script>标签)放在名为myJs.js的文件中,并使其可以从浏览器加载。