Javascript 使用成功的 Ajax 请求重定向页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3513971/
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
Page redirect with successful Ajax request
提问by Amit
I have a form that uses Ajax for client-side verification. The end of the form is the following:
我有一个使用 Ajax 进行客户端验证的表单。表格的结尾如下:
$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
        success: function(result) {
            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();
            });
        }
    });
EDIT: this is my mail3.php file dealing with errors:
编辑:这是我处理错误的 mail3.php 文件:
$errors=null; 
if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}
if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    //header ("Location: thankyou.html");
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html
} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}
I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?
我想知道如果 ajax 请求成功并且不存在错误,是否可以将用户重定向到谢谢页面。这可能吗?
Thanks! Amit
谢谢!阿米特
采纳答案by Adam
Sure. Just put something at the the end of your success function like:
当然。只需在成功函数的末尾放一些东西,例如:
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
where your server returns the response no_errorswhen there are no errors present.
no_errors当不存在错误时,您的服务器将返回响应。
回答by TJ L
Just do some error checking, and if everything passes then set window.locationto redirect the user to a different page.
只需进行一些错误检查,如果一切都通过,则设置window.location为将用户重定向到不同的页面。
$.ajax({
    url: 'mail3.php',
    type: 'POST',
    data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
    success: function(result) {
        //console.log(result);
        $('#results,#errors').remove();
        $('#contactWrapper').append('<p id="results">' + result + '</p>');
        $('#loading').fadeOut(500, function() {
            $(this).remove();
        });
        if ( /*no errors*/ ) {
            window.location='thank-you.html'
        }
    }
});
回答by Nick Craver
You can just redirect in your successhandler, like this:
您可以在success处理程序中重定向,如下所示:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
或者由于您正在显示结果,请等待几秒钟,例如这将等待 2 秒钟:
setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);
回答by Jeremy Boyd
In your mail3.php file you should trap errors in a try {} catch {}
在您的 mail3.php 文件中,您应该在 try {} catch {} 中捕获错误
try {
    /*code here for email*/
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
}
Then in your successcall you wont have to worry about your errors, because it will never return as a success.
然后在你的success通话中你不必担心你的错误,因为它永远不会成功返回。
and you can use: window.location.href = "thankyou.php";inside your success function like Nick stated.
你可以使用:window.location.href = "thankyou.php";在你的成功函数中,就像尼克说的那样。
回答by morels
$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
        success: function(result) {
            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();
            });
            if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
        }
    });
回答by Nitin Hurkadli
I posted the exact situation on a different thread. Re-post.
我在另一个线程上发布了确切的情况。重新发帖。
Excuse me, This is not an answer to the question posted above.
对不起,这不是上面发布的问题的答案。
But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.
但是带来了一个有趣的话题——何时使用 AJAX,何时不使用 AJAX。在这种情况下,最好不要使用 AJAX。
Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?
让我们举一个简单的登录名和密码示例。如果登录名和/或密码不匹配,使用 AJAX 报告一条简单的消息说“登录不正确”会很好。但是如果登录名和密码是正确的,为什么我必须回调一个 AJAX 函数来重定向到用户页面?
In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...
在这种情况下,我认为使用简单的表单提交会很好。如果登录失败,重定向到 Relogin.php,它看起来与 Login.php 相同,在 url 中带有 GET 消息,如 Relogin.php?error=InvalidLogin... 类似的东西...
Just my 2 cents. :)
只有我的 2 美分。:)
回答by Aram Mutlu
Another option is:
另一种选择是:
window.location.replace("your_url")
回答by MilkyWayJoe
I think you can do that with:
我认为你可以这样做:
window.location = "your_url";
回答by simnom
I suppose you could attack this in two ways;
我想你可以通过两种方式攻击它;
1) insert window.location = 'http://www.yourdomain.cominto the success function.
1)插入window.location = 'http://www.yourdomain.com成功函数。
2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/
2)使用进一步的ajax调用并将其注入页面上的元素中,您可以在http://api.jquery.com/jQuery.get/的jQuery文档中找到更多信息
回答by Rex CoolCode Charles
// Create lag time before redirecting 
setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);
$errors=null; 
if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}
if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html
    // redirect
    setTimeout();
} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

