You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用Fetch API调用Yii2控制器方法时isAjax返回false?

Yii2中Fetch API调用时isAjax返回false的原因及解决办法

问题场景

前端使用Fetch API调用Yii2控制器方法,代码如下:

fetch(url, {
    //method: 'GET',
    //body: dati,
    //headers: {
        //'Content-type': 'application/x-www-form-urlencoded'
    //}
}).then(function (response) {
    if (response.ok) {
        return response;
    } else {
        return Promise.reject(response);
    }
}).then(function (data) {
    console.log(data);
}).catch(function (error) {
    console.warn('Something went wrong.', error);
});

请求URL:cart/update-cart?id=13&action=add

控制器代码:

public function actionupdateCart(int $id, string $action){
    if (Yii::$app->request->isAjax) {
        return json_encode('Ajax call');
    } else {
        return json_encode('Not Ajax call?');
    }
}

预期返回'Ajax call',但实际得到'Not Ajax call?',疑问为何isAjax的值为false。

原因分析

Yii2的request->isAjax判断逻辑是检查请求头中是否存在X-Requested-With: XMLHttpRequest,而Fetch API默认不会自动携带这个请求头,所以Yii无法识别该请求为Ajax请求,导致isAjax返回false。

另外注意:你的控制器方法名actionupdateCart不符合Yii2的驼峰命名规范(正确应为actionUpdateCart),当前请求能进入方法说明路由匹配暂时没问题,但为了规范建议修正。

解决办法

在Fetch请求的headers中手动添加X-Requested-With头:

fetch(url, {
    method: 'GET',
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    }
}).then(function (response) {
    if (response.ok) {
        return response.text(); // 如需解析JSON可改用response.json()
    } else {
        return Promise.reject(response);
    }
}).then(function (data) {
    console.log(data);
}).catch(function (error) {
    console.warn('Something went wrong.', error);
});

添加该请求头后,Yii2就能正确识别请求为Ajax类型,isAjax会返回true,控制器将返回预期的'Ajax call'。

内容的提问来源于stack exchange,提问作者law_81

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:28:23