使用setTimeout重定向Javascript

时间:2012-08-14 21:25:15

标签: javascript redirect settimeout

我有一个按钮,我想运行一段脚本,然后重定向,但没有发生任何事情

我有另一个页面使用类似的代码并且有效。但这个只是不起作用

要运作的代码:

<a href="javascript:void(0);" onclick='$.get("features.php",{ cmd: "confirm_order", id: "<?php echo $o_id; ?>", name: "<?php echo $_SESSION['user_name']; ?>" email: "<?php echo $_SESSION['user_email']; ?>"};setTimeout("window.location.href=order.php?order_id=<?php echo $o_id;?>", 100);' class="button">

已在其他页面上运行的代码:

<a href="javascript:void(0);" onclick='$.get("features.php",{ cmd: "remove", id: "<?php echo $o_id; ?>", prod: "<?php echo $row_prod['prod_id']; ?>" });setTimeout("window.location.href=window.location.href", 100);'>

现在我知道这与我的setTimeout有关,我只是不确定我做错了什么。

修改

立即链接:

<a href="javascript:void(0);" class="button confirm">Confirm</a>

链接下面的代码:

<script type="text/javascript">
$('a .confirm').on('click',function(e){
    $.get("features.php",{
        cmd: "confirm_order",
        id: "<?php echo $o_id; ?>",
        name: "<?php echo $_SESSION['user_name']; ?>",
        email: "<?php echo $_SESSION['user_email']; ?>"
    });
    setTimeout(
        function(){
            window.location = "order.php?order_id=<?php echo $o_id;?>" 
        },
    100);
});
</script>

仍然无效,并且正在代码

中呈现\"

3 个答案:

答案 0 :(得分:3)

我同意Felix Kling的观点,即你不应该在html属性中添加那么多代码。我看到你正在使用jQuery,所以为什么不把它添加到你的javascript代码中:

$('a .button').on('click',function(e){
    $.get("features.php",{ 
          cmd: "confirm_order",
          id: "<?php echo $o_id; ?>",
          name: "<?php echo $_SESSION['user_name']; ?>", // you were missing this comma 
          email: "<?php echo $_SESSION['user_email']; ?>"
        }).done(function(){
             window.setTimeout( function(){
                 window.location = "order.php?order_id=<?php echo $o_id;?>";
             }, 100 );
        }); // you where missing this parenthesis          

  e.preventDefault(); 
});

答案 1 :(得分:2)

尝试将文件名置于"之间(您可以使用\"将其转义):

setTimeout("window.location.href=\"order.php?order_id=<?php echo $o_id;?>\";", 100);

您的文件名是一个字符串。否则JavaScript会期望变量。这就是setTimeout("window.location.href=window.location.href;", 100);有效的原因。

我认为还有一个逗号丢失:

name: "<?php echo $_SESSION['user_name']; ?>" email: "<?php echo $_SESSION['user_email']; ?>"

应为name: "<?php echo $_SESSION['user_name']; ?>", email: "<?php echo $_SESSION['user_email']; ?>"

您也缺少一个括号。尝试将您的代码更改为:

<a href="javascript:void(0);" onclick='$.get("features.php",{ cmd: "confirm_order", id: "<?php echo $o_id; ?>", name: "<?php echo $_SESSION['user_name']; ?>", email: "<?php echo $_SESSION['user_email']; ?>"});setTimeout("window.location.href=\"order.php?order_id=<?php echo $o_id;?>\";", 100);return false;' class="button">

答案 2 :(得分:1)

试试这个

<script type="text/JavaScript">
redirectTime = "1500";
redirectURL = "http://www.natural-environment.com";
function timedRedirect() {
    setTimeout("location.href = redirectURL;",redirectTime);
}
</script>