【问题标题】:Ajax PHP Redirect to a url [duplicate]Ajax PHP重定向到一个url [重复]
【发布时间】:2018-01-15 21:44:00
【问题描述】:

我想在使用 ajax 调用的 php 文件中进行重定向。在文件中我写了重定向。但是重定向代码不起作用。

这是ajax文件的代码:

<?php
ob_start();
include 'admin/includes/front_controller.php';

if (isset($_POST['id'])) {
    $job_id = intval($_POST['id']);
    $job_id = 30;
    $jobdetail = $db->getTableWhere("jobs", "jbid", $job_id);
    $count = count($jobdetail);
    if ($count <= 0) {
        header("Location: jobs.php");
        exit();
    }
} else {
    echo "There is an error processing your request";
}
?>

这是我正在使用的 ajax 调用:

<script type="text/javascript">
    $(".job-btn").on('click', function (e) {
        e.preventDefault();
        var id = $(this).data('id');
        //alert(id);
        var url = "<?php echo SITE_URL; ?>" + "jobdetail.php";
        var info = 'id=' + id;
        $.ajax({
            type: "POST",
            url: url,
            data: info,
            success: function (data) {
                alert(data);

            },
            error: function (data) {
                //alert(data.responseText);
                //alert("Error occured in showing details");
            }
        })

    });
</script>

【问题讨论】:

  • 你不能从 ajaxed 页面重定向
  • 您的 ajax 响应应该包含重定向回调的说明,即 URL 应该在 JSON 中
  • 重定向永远不会在 AJAX 中发生。您必须在 success: function(data) {.... 中编写重定向代码

标签: php jquery ajax


【解决方案1】:

成功函数中使用js重定向

success: function (data) {
   alert(data);
   window.location ="jobs.php";
 },

【讨论】:

    【解决方案2】:

    代替:

    header("Location: jobs.php");
    

    在php代码中,将response中的url返回给ajax。并在success 中使用window.location,例如:

     success: function (response) {
         window.location = response;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2021-02-05
      • 2012-05-14
      • 2015-03-06
      • 2016-06-26
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多