在 ajax 请求后执行 PHP 重定向

Execute PHP redirect after ajax request

对于银行应用程序,如果(且仅当)访问令牌无效时,我需要将用户重定向到外部登录页面。此重定向只能从服务器触发,因为此访问令牌永远不会发送到客户端。

PHP 看起来像这样(使用 Slim 框架):

$app->get( '/banking', function ( \Slim\Http\Request $request, \Slim\Http\Response $response, $args ) {
    if( token == valid ) {
      // do your stuff
    } else {

        $banking = new Banking();
        $connection = $banking->getConnection();
        return $response->withHeader( 'Location', $connection->login_url( 'someRandomString' ) );
        }
    } );

$connection->login_url() 生成我要重定向到的 URL。 jQuery 然而并没有将我重定向到该页面,而是将页面内容加载到成功回调函数的响应字符串中。 (我读过 here 浏览器会默默地跟随重定向)

有没有办法强制客户端实际重定向页面或帮助 javascript 发现它实际上应该重定向到外部页面而不是将内容加载到脚本中?怎么样?

也将状态设置为 302,以便浏览器进行重定向。

$response = $response->withStatus(302);
return $response->withHeader('Location', $connection->login_url( 'someRandomString' ) );

或者,当您使用 Slim 时,您可以使用 withRedirect:

return $response->withRedirect($connection->login_url('someRandomString'));