Ajax 在新页面上重定向并在显示成功消息后

Ajax Redirect on new page and after display success message

我正在与 ajax 和 php 合作。我想在使用 Ajax 成功添加用户后在另一个页面上显示消息。我已经尝试了很多。当第一次在弹出窗口上显示 "Success" 消息并在另一个页面上重定向时,它正在工作。但我想先在另一个页面上重定向,然后显示消息。

用户添加页面:

<form action="<?php echo $action_link; ?>" method="post" id="form_user_profile" class="form-horizontal" novalidate="novalidate">

   <input type="hidden" id="id" name="id" value="<?php echo $id; ?>">

   <div class="form-body">
     <div class="form-group">
       <label class="control-label col-md-3">First Name
         <span class="required" aria-required="true"> * </span>
       </label>
       <div class="col-md-4">
         <div class="input-icon right">
           <i class="fa"></i>
           <input type="text" class="form-control" name="fname" value="<?php echo $user_db[0]['fname']; ?>"> 
         </div>
       </div>
     </div>
     <div class="form-actions">
       <div class="row">
         <div class="col-md-offset-3 col-md-9">
           <input type="submit" class="btn green" name="submit" value="<?php echo $addupdate_msg; ?>">
         </div>
       </div>
     </div>
</form>

Ajax 验证

$("#form_user_profile").validate({
        rules: {
            fname: {
                required: true
            }
        },
        messages: {
            fname: "Please enter first name"
        },
        submitHandler: function(form) {
            $.ajax({
                url: form.action,
                type: form.method,
                data: $(form).serialize(),
                success: function(response) {
                    if(response == 1){
                        bootbox.alert("User has been added successfully.", function() {
                            window.location.href= "<?php echo $user_list; ?>";
                        });
                    }
                }
            });
        }
});

动作

if (isset($_REQUEST['submit']) && $_REQUEST['submit'] == "Add") {

    $fname = mysqli_real_escape_string($obj->CONN, $_REQUEST['fname']);    

    $user->setfname($fname);
    $insert = $user->insert();

    ob_get_clean();

    if($insert){
        echo '1';
        $_SESSION['msg'] = "New user has been added successfully.";
    }else{
        echo '0';
    }

    exit;
}

由于以下代码,在用户重定向之前出现成功弹出窗口:

if(response == 1){
    bootbox.alert("User has been added successfully.", function() {
        window.location.href= "<?php echo $user_list; ?>";
    });
}

如果您希望在新页面上显示消息,只需重定向用户

if(response == 1)window.location.href= "<?php echo $user_list; ?>";

新页面 成功后发送给客户的地方,显示消息类似

$(function() {
    bootbox.alert(<?= $_SESSION['msg'] ?>);
});

您可以检查是否在您指向的页面上设置了 $_SESSION['msg'],如果设置了则 alert

Jquery:

if(response == 1){window.location.href= "<?php echo $user_list ?>";}

然后,$user_list 页:

if(isset($_SESSION['msg'])){
  echo '$(document).ready(function(){
            bootbox.alert('.$_SESSION['msg'].');
        })';
}

注意,我使用了单引号,这样 PHP 就不会认为 $ 是一个变量。