我有一个函数可以使用以下命令从服务器重新加载
:serialVersionUID
当前,此行之后的所有代码都不会执行。
我很好奇,是否有办法在重新加载后 后运行更多代码?
答案 0 :(得分:0)
最好的方法是编写一个设置了某些“ GET”变量的函数,并在每次运行时检查它们,例如mypage.html?reload=true
甚至是哈希位置:mypage.html#reload
您可以像这样进行比较:
$(document).ready(function () {
if (window.location.hash == '#reload') {
onReload();
}
});
function onReload () {
console.log('test');
}
function reload () {
window.location.hash = 'reload';
window.location.reload();
}
只需调用reload();
函数。
输出(在控制台中):test
然后,如果您不希望在再次刷新页面后运行函数,则可以将人员从哈希#reload
重定向:window.location.hash = '';
答案 1 :(得分:-1)
为什么重新加载页面后需要执行某些操作?
如果在重新加载后需要执行某些操作,则可以将一些参数传递给页面,然后选中此参数以执行其他操作。您可以重定向到同一页面并传递完整的URL
var url = window.location.href;
url += '¶m=1'
window.location.href = url;
因此,在重新加载页面时,您可以通过 GET 检查参数,然后执行所需的任何操作。我希望这个技巧对您有帮助!
答案 2 :(得分:-1)
________________方法1:使用PHP _________________
1)使用参数重新加载
2)使用PHP获取该参数
例如:
window.location.href += '&reloading=1';
//it's equivalent to:
//window.location.href = window.location.href + '&reloading=1';
然后:
<?php
if (isset($_GET['reloading'])) {
echo '<script>pageReloaded();</script>';
}
?>
由于将首先执行PHP,因此将编写该小脚本(该函数调用),然后在javascript中执行,因此将调用pageReloaded()函数。
一个完整的例子是:
<?php if (isset($_GET['reloading'])) echo '<script>pageReloaded();</script>'; ?>
<script>
function reloadNow(){
alert("I'm about to reload");
window.location.href += '&reloading=1';
}
function pageReloaded(){
alert("I've been reloaded!");
}
</script>
<button onclick="reloadNow()">Press to reload</button>
________________方法2:不使用PHP,仅JAVASCRIPT _________________
1)设置SessionStorage。
2)重新加载
3)获取该SessionStorage
例如:
<script>
function reloadNow(){
alert("I'm about to reload");
sessionStorage.setItem('reloading',"true");
window.location.reload(true);
}
//when loading:
if (sessionStorage.getItem('reloading') === "true") {
sessionStorage.clear(); //so it doesn't trigger next time
alert("I've been reloaded!");
}
</script>
<button onclick="reloadNow()">Press to reload</button>