【问题标题】:Ajax request postingAjax 请求发布
【发布时间】:2014-04-07 14:13:34
【问题描述】:

我为我糟糕的英语道歉:)

我正在使用 ajax 请求做 php 文件。 json 响应的格式为。但在某些情况下可以重定向。在这种情况下,我想要页面的重定向。

你能帮帮我吗?谢谢。

示例 PHP 文件:

<?php
$status = $_POST['status'];

if($status == 'a'){
    // return json response
}else{
   echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>

示例 JS 文件:

$.ajax({
  type: "POST",
  url: 'http://www.my_php_file.com'
});

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    使用成功函数https://api.jquery.com/jQuery.ajax/

    $.ajax({
      type: "POST",
      url: 'http://www.my_php_file.com'
     data: { status : statusVar },
    success: function(response){
    if (response.status == 'a'){
    $( "#results" ).append( response);
    }else{
    window.location = 'http://www.url.com'
    }
    });
    });
    

    【讨论】:

      【解决方案2】:

      试试这个。

      url: "http://www.my_php_file.com",
      success: function(data) {
            document.location.href='YouNewPage.php';
      }
      

      【讨论】:

        【解决方案3】:

        需要检测响应数据是否为有效的JSON:

        $.ajax({
          type: "POST",
          url: 'http://www.my_php_file.com',
          success: checkAJAX
        });
        
        function checkAJAX(data)
        {
            var response = $.parseJSON(data);
            if(typeof response === "object")
            {
            }
            else
            {
                // If the AJAX response is not JSON, append the HTML to the document
                $('body').append(data);
            }
        }
        

        【讨论】:

          【解决方案4】:

          将您想要回显的 html 也返回为 JSON:

          if($status == 'a'){
             // return json response
          } else {
             echo json_encode(array("redirect" => "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>"));
          }
          

          并在 ajax 响应中检查 redirect

          $.ajax({
             type: "POST",
             dataType: "json",
             url: 'http://www.my_php_file.com',
             success: function(data) {
                if(typeof data.redirect !== "undefined") {
                   $("body").append(data.redirect);
                }
             }
          });
          

          只有两个提醒,如果请求失败将不会重定向(没有 fail 回调),我假设您的随意 JSON 响应没有属性 redirect

          【讨论】:

          • 将 HTML 作为“JSON”返回,其中包含一个可以自行提交的表单,......这是有史以来最糟糕的建议。你应该总是返回 JSON,然后在 JavaScript 中采取相应的行动。您可以在一个 ajax 请求中执行第二个 ajax,但永远不要返回 HTML :-S
          • 我实际上就像你说的那样行事(可悲的是不是在这里),但是我不知道表单有什么,在这种情况下脚本在做什么,所以我就这样离开了曾是。我也不想将 HTML 作为 JSON 返回。
          猜你喜欢
          • 2020-10-30
          • 1970-01-01
          • 2015-07-24
          • 2021-03-24
          • 2013-09-16
          • 2011-06-02
          • 2016-06-28
          • 2014-05-14
          • 2017-12-24
          相关资源
          最近更新 更多