我的标签链接是这样的:
<a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a>
当点击链接主页时,它会调用仪表板。调用仪表板时,我想检查 session 。如果 session 存在,调用仪表板。如果 session 不存在,则注销
我的 javascript 代码是这样的:
$(".check_session").click(function() {
$.ajax({
url: base_url+"shared/check_session/"+Math.random()+new Date().getTime(),
success: function(response){
if(response == 'out')
{
alert('Please login');
window.location.href = base_url + "logout";
}
}
});
});
我的问题:
当链接主页被点击时,它没有调用检查 session 功能
有什么办法可以解决我的问题吗?
非常感谢
最佳答案
你需要有一个 event.preventDefault()
来停止 anchor 的默认行为:
$(".check_session").click(function(e) { // <-----get the event here
e.preventDefault(); //<--------here stop the default behavior
var url = this.href; // <---get the url
$.ajax({
url: base_url+"shared/check_session/"+new Date().getTime(),
success: function(response){
if(response == 'out'){
alert('Please login');
window.location.href = base_url + "logout";
}else{
window.location.href = url; // <----navigate to it here.
}
}
});
});
问题是,当您单击此 anchor 时,它会导航到指定的 href
,因此您的 ajax 永远不会被调用。在这种情况下,如果您在 anchor 上绑定(bind)了任何事件,请确保使用 event.preventDefault()
停止默认行为。
虽然不需要 Math.random()
new Date().getTime()
会这样做。
关于javascript - 如何在一个标签中调用两个 Action 链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739908/