# Yii2中redirect ajax请求不跳转

**URL:** <https://www.shiqidu.com/t/topic/392>\
**Category:** 开发调优\
**Tags:** Yii\
**Created:** [2018 年4 月 3 日 03:23 UTC](https://www.shiqidu.com/t/topic/392 "2018-04-03T03:23:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2018 年4 月 3 日 03:23 UTC](https://www.shiqidu.com/t/topic/392/1 "2018-04-03T03:23:48Z")

</div>

现有逻辑是后台不登录的情况下所有请求都跳转到登录页。

```php
public function beforeAction($action)
{
    if (Yii::$app->user->getIsGuest() && !in_array($action->id, self::$ignoreList)) {
        $this->redirect(Yii::$app->user->loginUrl);
    }
    return parent::beforeAction($action);
}

```

这么写在不是ajax请求的情况下是好用的。但是如果是ajax请求，这么写就不行了。所以修改如下。

```php
public function beforeAction($action)
{
    if (Yii::$app->user->getIsGuest() && !in_array($action->id, self::$ignoreList)) {
        $this->redirect(Yii::$app->user->loginUrl)->send();
    }
    return parent::beforeAction($action);
}

```

加上send方法后发现ajax请求竟然正常跳转了，这特么太神奇了啊。后来发现YII2在相应体中放了一个`X-Redirect`，值就是登录地址。

那么浏览器是怎么根据这个`X-Redirect`跳转的呢。我并没有写跳转的代码。

后天来查阅文档发现，只要你引入了·`yii.js`，那么这货会帮你过滤所有的ajax请求。

```javascript
function initRedirectHandler() {
    // handle AJAX redirection
    $(document).ajaxComplete(function (event, xhr) {
        var url = xhr && xhr.getResponseHeader('X-Redirect');
        if (url) {
            window.location.assign(url);
        }
    });
}

```

这个js里封装了一些常用的函数，还是挺方便的。
