Javascript Redirect with SetTimout Not Working

♀尐吖头ヾ 提交于 2019-12-11 05:46:14

问题


Can't seem to get this javascript redirect to work? Suggestions?

Should I maybe do it with a meta refresh and how?

// If we have a successful location update
function onGeoSuccess(event)
{
    document.getElementById("Latitude").value =  event.coords.latitude; 
    document.getElementById("Longitude").value = event.coords.longitude;
    document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;

var redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude; 

}

// If something has gone wrong with the geolocation request
function onGeoError(event)
{
    alert("Error code " + event.code + ". " + event.message);
}

function redirect() 
     { 
    window.location = redirectUrl; 
     } 
    setTimeout(redirect,15000); 

回答1:


The problem is the scope of redirectUrl variable. You declared redirectUrl as local for onGeoSuccess function, so it will be visible only inside of it. For workaround ,you can put all this stuff:

function redirect() 
{ 
    window.location = redirectUrl; 
} 
setTimeout(redirect,15000);

inside of onGeoSuccess function, or make redirectUrl global, by removing var before redirectUrl:

     redirectUrl = "track.cfm?track=s&Lat="+...
//^-----no 'var'



回答2:


Declare redirectUrl in parent scope, and run onGeoSuccess function.

var redirectUrl;

function onGeoSuccess (event) {
  document.getElementById("Latitude").value =  event.coords.latitude; 
  document.getElementById("Longitude").value = event.coords.longitude;
  document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;

  redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude; 

}

function onGeoError (event) {
  alert("Error code " + event.code + ". " + event.message);
}

function redirect () { 
  window.location = redirectUrl; 
} 

onGeoSuccess(...);
setTimeout(redirect, 15000);



回答3:


Two problems:

1) The redirect URL is being set by a function which, at least from the code you posted, is not being called

2) Even if it was called, redirectUrl is a local variable to that function, so the timeout cannot access it.

Always check the error console.



来源:https://stackoverflow.com/questions/11702088/javascript-redirect-with-settimout-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!