我有一个 Razor View 页面,如果我在系统的 session 存储中有一个值,我想加载一些数据。我有以下 cshtml
<main class="admin-main" onreadystatechange="testMe">
<!--Hidden content here-->
</main>
testMe
是我在外部 javascript 文件中定义的回调,如下所示:
function testMe() {
if (document.readyState === 'loading') {
console.log("Admin page accessed");
if (sessionStorage.getItem('special')) {
return;
}
else {
window.location.href = "/Home/SpecialLogin";
}
}
}
当我在 chrome 中运行它时,没有任何反应,因为 javascript 从未执行。我尝试同时使用 testMe
和 testMe()
但没有成功。
我什至尝试将其包含在脚本标记和页面底部,但仍然没有响应。断点永远不会触发。
是否有某种我超越的 MVC 方法可以做到这一点?使用独立的 html/css/js 运行它效果很好。
最佳答案
根据documentation ,当文档的 readyState
属性发生更改时,会触发 readystatechange
事件。 main
标记没有 readyState
属性。
如果您希望在文档的 readyState
更改时运行该代码,您可以像这样使用 jQuery:
$(document).on('readystatechange', function() {
if (document.readyState === 'loading') {
console.log("Admin page accessed");
if (sessionStorage.getItem('special')) {
return;
}
else {
window.location.href = "/Home/SpecialLogin";
}
}
});
关于Javascript 回调未在 razor MVC 中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47022773/