首页 > 解决方案 > 如果管理员从另一个页面按下提交按钮,如何重定向用户?

问题描述

起初对不起我的英语。

我在 admin.php 页面上创建了一个管理面板,其中有这样的表单:

<form action="#" method="post">
<button type="submit" name="submit">
</form>

提交将 TRUE 发送到数据库并将其存储在那里。这是我被卡住的部分。

在另一个页面 user.php 有一个这样的用户表单:

<form action="loading.php" method="post">
<input type="text" name="email">
<button type="submit" name="submit">
</form>

用户填写表格后,他的数据也会发送到数据库。之后,他会被重定向到正在加载屏幕上等待的 loading.php。

用户知道必须等到管理员将 TRUE 发布到数据库。这部分需要实时,因此用户正在加载屏幕上等待,当管理员将表单提交到数据库时,用户会被实时重定向,因此他不需要刷新页面。执行此类操作的最佳方法是什么?我可以在 AJAX 中设置一个带有间隔的计时器来检查它吗?那么我该如何执行呢?

提前致谢。

标签: javascriptphpajax

解决方案


PHP端:

<?php // checkstatus.php
$user_id = $_GET['user_id'];
assert(is_numeric($user_id));

// Whatever query engine you use.
$query = 'select redirect where user_id = %user_id';
$results = runQuery($query, array('%user_id' => $user_id);
$redirect = $results->getvalue('redirect');

$response = array(
  'redirect' => $redirect,
);

header('Content-Type: application/json');
echo json_encode($response, JSON_PARTIAL_OUTPUT_ON_ERROR);
die();

Javascript 方面(我只用 jquery 完成了这个,所以检查一下香草https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/):

function checkRedirect()
{
  $.Get('/checkstatus.php', {user_id: 10}, function(response)
  {
    if (response['redirect'])
    {
      window.location.href = '/newpage.php';
    }
  }, 'json').error(function()
  {
    // Something broke notify the user somehow. Please don't use alert.
    clearInterval(interval);
  });
}

// Must set this in global scope or interval will not be accessible inside error.add
interval = setInterval(checkredirect, 5000);

推荐阅读