settimeout没有被调用?

时间:2015-04-27 08:26:30

标签: javascript settimeout

我有一个调用服务器并获取JSON数据的javascript,其中包含一些配置以启用/禁用重定向到另一个链接。我需要将重定向延迟几秒钟,但似乎没有在我的方法中调用setTimeout()。即使我将redirect()更改为匿名函数并在setTimeout中传递它仍然没有被调用。

<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {   
    function redirect(){
        alert("in redirect");
        window.top.location=migrationConfig.REDIRECT_LINK;
    }       
    if (xhr.readyState == 4 && xhr.status==200) {
        var data = xhr.responseText;
        migrationConfig = JSON.parse(data);
        if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
            if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
                document.body.innerHTML = '';
                document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
                document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");                            
                setTimeout(redirect,3000);
            }

        }

    }
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

2 个答案:

答案 0 :(得分:1)

//设置全局对象以在settimeout函数中使用它

var redirect;

然后在xhr.onreadystatechange = function(){

redirect = function(){
alert("in redirect");
        window.top.location=migrationConfig.REDIRECT_LINK;
}

setTimeout('redirect()',3000);

答案 1 :(得分:0)

感谢所有建议。我根据talsibony的建议改进了它,并且我还发现document.write()删除了我的所有内容,这使得它无法找到重定向全局变量。所以我改为添加div元素并设置innerHTML。如果有人遇到类似问题,这是固定代码。

<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;

xhr.onreadystatechange = function() {       
    redirect = function(){
        window.top.location=migrationConfig.REDIRECT_LINK;
    }       


    if (xhr.readyState == 4 && xhr.status==200) {
        var data = xhr.responseText;
        migrationConfig = JSON.parse(data);
        if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
            if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
                document.body.innerHTML = '';
                var div = document.createElement("div");                    
                document.body.insertBefore(div, document.body.firstChild);
                div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
                div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
                div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
                setTimeout(redirect,3000);
            }

        }

    }
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

相关问题