【问题标题】:Page redirect with successful Ajax request使用成功的 Ajax 请求进行页面重定向
【发布时间】:2011-03-31 15:34:20
【问题描述】:

我有一个使用 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();

            });

        }
    });

编辑:这是我处理错误的 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>";
}

我想知道如果 ajax 请求成功并且没有错误出现,是否可以将用户重定向到感谢页面。这可能吗?

谢谢! 阿米特

【问题讨论】:

  • @Andrea:这不是重复的,因为我仅在不存在错误时才尝试重定向页面。如果出现错误,我希望它写出这些错误。
  • 这能回答你的问题吗? How do I redirect a page in jQuery?
  • 我说它是重复的。问题的本质是如何重定向,可以在链接的问答中看到,你可以在这里使用的代码,在测试任何你需要测试的东西以确定没有错误之后。事实上,在明显的“如果”检查之后,here 的每个答案都与 there 的答案一样。

标签: javascript jquery ajax redirect


【解决方案1】:

您可以在 success 处理程序中重定向,如下所示:

window.location.href = "thankyou.php";

或者由于您正在显示结果,请等待几秒钟,例如这将等待 2 秒钟:

setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

【讨论】:

  • 你能看看我的编辑,看看我如何处理没有错误的情况吗?如果没有错误,我只希望它被重定向到thankyou.php。
  • @Amit - 你可以把if(result === "Your message was successfully sent!")放在这之前,那只会在那些情况下发送。
【解决方案2】:

我认为你可以这样做:

window.location = "your_url";

【讨论】:

    【解决方案3】:

    我想你可以通过两种方式来攻击它;

    1) 在成功函数中插入window.location = 'http://www.yourdomain.com

    2) 使用进一步的 ajax 调用将其注入页面上的元素中,您可以在 http://api.jquery.com/jQuery.get/ 的 jQuery 文档中找到更多信息

    【讨论】:

      【解决方案4】:

      当然。只需在成功函数的末尾添加一些内容,例如:

      if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
      

      当不存在错误时,您的服务器返回响应 no_errors

      【讨论】:

      • 正确使用 HTTP 状态码将使每次成功都取得成功,而无需服务器回传任何消息。
      • @Jeremy- 是的,除非您想传回特定的错误消息以供站点处理,甚至是在失败时重定向到不同的 URL。这些消息必须返回一个 200 响应代码,需要一个 no_errors 响应来区分。
      • 其实乍一看,我觉得这种方法可行!
      • 是否可以获取从 mail3.php 文件返回的 $error 变量(请参阅编辑)并检查其内容。 if !($error),然后重定向页面?
      • @Adam - 不一定。 jQuery 的 Ajax 对象中的错误函数仍然可以访问响应的响应文本。
      【解决方案5】:

      只需进行一些错误检查,如果一切顺利,则设置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'
              }
      
          }
      });
      

      【讨论】:

      • 如果所有错误都通过mail3.php文件处理,如何检查无错误情况?
      • 您应该在 mail3.php 文件中捕获错误,并在响应中返回状态代码 500。
      • 您能详细说明一下吗?我究竟如何返回这个状态码 500?
      • 是否可以获取从 mail3.php 文件返回的 $error 变量(请参阅编辑)并检查其内容。如果 !($error),则重定向页面
      • @Amit 我会做类似 if(result === "Your message was successfully sent!")//redirect else $('#id ofEmptyDivOnPage').html(response) 这样的事情如果有错误,则在页面上显示错误,如果没有假设您有一个具有该 id 的 div 则重定向
      【解决方案6】:

      在您的 mail3.php 文件中,您应该在 try {} catch {} 中捕获错误

      try {
          /*code here for email*/
      } catch (Exception $e) {
          header('HTTP/1.1 500 Internal Server Error');
      }
      

      然后在您的success 电话中,您不必担心您的错误,因为它永远不会返回成功。

      你可以像尼克所说的那样在你的成功函数中使用:window.location.href = "thankyou.php";

      【讨论】:

        【解决方案7】:
        // 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>";
        }
        

        【讨论】:

          【解决方案8】:

          我在另一个帖子上发布了确切的情况。重新发布。

          对不起,这不是上面发布的问题的答案。

          但是带来了一个有趣的话题——什么时候使用AJAX,什么时候不使用AJAX。在这种情况下,最好不要使用 AJAX。

          让我们举一个简单的登录名和密码示例。如果登录名和/或密码不匹配,最好使用 AJAX 报告“登录错误”的简单消息。但是如果登录名和密码都是正确的,为什么还要回调一个AJAX函数来重定向到用户页面呢?

          在这种情况下,我认为使用简单的表单提交会很好。如果登录失败,重定向到 Relogin.php,它看起来与 Login.php 相同,在 url 中带有 GET 消息,如 Relogin.php?error=InvalidLogin... 类似的东西...

          只有我的 2 美分。 :)

          【讨论】:

            【解决方案9】:
            $.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"
            
                    }
                });
            

            【讨论】:

              【解决方案10】:

              另一种选择是:

              window.location.replace("your_url")
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-12-27
                • 1970-01-01
                • 2015-04-08
                相关资源
                最近更新 更多