gpt4 book ai didi

javascript - 从文件中提取 AJAX

转载 作者:行者123 更新时间:2023-11-30 18:03:37 24 4
gpt4 key购买 nike

在我提出的另一个问题的帮助下让我的 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>

最佳答案

使用此标记加载 javascript。把它放在 HTML 的底部,就在 </html> 之前

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

然后您必须将 javascript(不带 <script> 标记)放入名为 myJs.js 的文件中,并使其可从浏览器加载。

关于javascript - 从文件中提取 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com