刷新JS脚本而不重新加载页面

refresh JS Script without reloading the page

本文关键字:加载 新加载 脚本 JS 刷新      更新时间:2023-09-26

我在我的网站上使用一个免费的天气预报小工具。

<script type="text/javascript" src="http://tools.tititudorancea.com/weather_forecast.js?place=zurich_2&amp;s=1&amp;days=5&amp;utf8=no&amp;columns=5&amp;temp=c"></script>
<div style="font: 10px Arial, sans-serif; color: #000000" align="right">
<a href="http://www.tititudorancea.com/z/weather.htm">Weather forecast</a> provided by <a href="http://www.tititudorancea.com/">tititudorancea.com</a></div>

我的网页将永远不会重新加载自己,然后天气将永远不会更新。有没有一种方法来刷新javascript不刷新所有页面?

Thanks in advance

你可以在url的末尾添加一个虚假的查询变量来强制刷新。首先给你的脚本标签添加一个id,然后试试这个:

var weather = document.getElementById('weather');
weather.src += '&bogus='+ new Date(); // init
setInterval(function() {
  weather.src = weather.src.replace(/&.+$/, '&bogus='+ new Date());
}, 1000);

这是我找到的解决方案。

var weatherURLSite = "http://tools.tititudorancea.com/weather_forecast.js?place=$placeID$&s=1&days=5&utf8=no&columns=5&temp=c";    
var specificWeather = weatherURLSite.replace("$placeID$", value);   
$.ajax({
            type: "POST",
            async: false,
            url: weatherURL,
            data: { url: specificWeather }
        }).done(
            function (content) {
                var li = "<li id='" + value + "'>" + content + creditsDiv + "</li>";
                $("#weather").append(li);                   
            });

我添加了一个计时器来周期性刷新

var weatherTimer = self.setInterval(function () { GetReloadWeather('@Url.Action("GetWeather","Weather")'); }, 3600000);

在我的项目中,我最终使用jQuery 'replaceWith'函数

jQuery("script").eq(2).replaceWith('<script type="text/javascript" src="/state.js"></script>');