我的标记链接是这样的:
<a href="<?php echo base_url().'dashboard' ?>" class="check_session">Home</a>
点击主页链接后,它将调用仪表板。当调用仪表板时,我想检查会话。如果存在会话,请调用仪表板。如果会话不存在,请注销
我的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";
}
}
});
});
我的问题:
点击链接主页时,没有呼叫检查会话功能
解决我问题的任何解决方案?
非常感谢
答案 0 :(得分:1)
您需要event.preventDefault()
来停止锚点的默认行为:
$(".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.
}
}
});
});
问题在于,当您单击此锚点时,它会导航到指定的href
,因此您的ajax永远不会被调用。在这种情况下,如果您已在锚点上绑定任何事件,请确保使用event.preventDefault()
停止默认行为。
虽然不需要Math.random()
new Date().getTime()
会这样做。
答案 1 :(得分:0)
如果你想采取行动,最好更改任何div的标签
和JS
$(".check_session").click(function() {
if(session = true)
{
window.location.href = base_url + "dashboard";
}
else
{
$.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";
}
}
});
}
});
和HTMl
<div class="check_session"> class="check_session">Home</a>
答案 2 :(得分:0)
在函数的第一行添加preventDefault()
,如果session为true,则添加else条件以重定向到仪表板
$(".check_session").click(function(e) {
var targeturl = $(this).attr('href');
e.preventDefault();
$.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";
}else{
window.location.href = targeturl;
}
});
});