Javascript ajax成功的window.location.href不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14213737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:03:04  来源:igfitidea点击:

window.location.href on ajax success not working

javascriptjqueryajax

提问by user1662927

I've been trying to solve this for a while now, but I can't get itworking. When a user clicks a link he's asked to confirm that he wants to take this action. Then a ajax call is made. The script that's called works fine and returns a string where to redirect to.

我一直试图解决这个问题一段时间了,但我无法让它工作。当用户单击链接时,系统会要求他确认是否要执行此操作。然后进行ajax调用。被调用的脚本工作正常并返回一个字符串重定向到哪里。

I've seen several posts here on problems with window.location, buth none of them could solve mine.

我在这里看到了几篇关于 window.location 问题的帖子,但没有一个能解决我的问题。

My code:

我的代码:

function confirm(a,b,c){
        var r=confirm("Are you sure to do this?");
        if(r==true){
            $.ajax({
                type: "POST",
                url: "/process-action.php",
                async: false,
                data: {a:a,b:b,c:c},
                success: function(data){
                    window.location.href = data;
                }
            });
        } else {
            return false;
        }
    }

If I do alert(data)instead of window.location.href = dataI can see that the correct data is passed. For instance /user/homepage. Yet, the redirection is not taking place.

如果我这样做alert(data)而不是window.location.href = data我可以看到传递了正确的数据。例如/用户/主页。然而,重定向没有发生。

If tried to replace the relative path with the entire url, but that didn't work either.

如果试图用整个 url 替换相对路径,但这也不起作用。

回答by Rory McCrossan

Try using assign()instead:

尝试使用assign()

window.location.assign(data);

window.location.hrefis a property, not a method.

window.location.href是一个属性,而不是一个方法。

回答by Sahal

Location assign()Method

位置assign()方法

The assign() method is supported in all major browsers.

回答by Rajesh Kakadiya

You can use this

你可以用这个

<form action="submit.php" onsubmit="return false;" method="post">

<form action="submit.php" onsubmit="return false;" method="post">

and your same script will be work.

并且您的相同脚本将起作用。

回答by Ram

You can also use window.location = "someurl";

你也可以使用 window.location = "someurl";