Redirecting to another page not working in javascr

2019-08-18 13:34发布

问题:

Hi folks. In my MVC application, I am trying to redirect to a login page, however it is not redirecting and I am getting a "server error".

Here is the javascript:

<script type="text/javascript"> 
function keepAlive() { 
window.clearTimeout(window.sessionKeepAlive); 
window.sessionKeepAlive = window.setTimeout(function() { 

    if(confirm('refresh session?')) { 
        // submit coding required 
    } else { 
        //window.location="/Employee/~/Account/LogOn"
        //location.replace("/Employee/~/Account/LogOn");
        window.location.href = '<%= Url.Action( "Logout", "Account" ) %>'; 
    } 

}, <%= (Session.Timeout - 19) * 60 * 1000 %>); 
} 
keepAlive(); 
</script>

Also, I need the code for if the user presses the 'ok' button and it continues.

回答1:

In my case, I prefer to add the full path link to web.config in

<appSettings>
    <add key="BaseURL" value="http://localhost/" />
</appSettings>

And declare an application variable in Global.asax in

protected void Application_Start()
{
    Application["BaseURL"] = System.Configuration.ConfigurationManager.AppSettings["BaseURL"];
}

And now I can use the variables in the whole site. In you case, you can simply use by

window.location.href = '<%=Application["BaseURL"]%>account/logout';


回答2:

Make sure that the location you're redirecting to includes the protocol i.e.

window.location.href = 'http://www.yoursite.tld/account/logout';

For the second bit you can make an ajax call to a heartbeat page to refresh the session

// simplified
try {
    var xhr = new XMLHttpRequest();
} catch( e ) {
    var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

xhr.open( 'get', 'http://heartbeat/url', true );
xhr.send( null );