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

如何在PHP(Yii2框架)中响应Ajax请求返回纯文本内容?

问题根源

Yii2默认启用了全局页面布局,控制器输出的内容会被自动嵌入预设的HTML布局模板中,因此会返回完整页面代码而非你输出的纯文本。

解决方案

方法1:控制器动作直接返回响应(最推荐)

遵循Yii2开发规范,关闭布局、设置响应格式为纯文本后直接返回内容即可:

// 对应控制器的动作方法,例:SiteController的actionTest
public function actionTest()
{
    // 关闭页面布局
    $this->layout = false;
    // 设置响应格式为原始纯文本
    \Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
    // 设置跨域头
    \Yii::$app->response->headers->set('Access-Control-Allow-Origin', '*');
    \Yii::$app->response->headers->set('Access-Control-Allow-Methods', '*');
    // 直接返回目标内容,框架会自动处理输出
    return 'My favourite color is red';
}

对应的前端ajax请求的url需要修改为该动作的路由地址,例如:

$.ajax({
    type: 'GET',
    // 路由对应控制器动作,可根据你的路由配置调整
    url: 'http://localhost:8080/index.php?r=site/test',
})
.done(function(data) {
    console.log('Results from PHP: ' + data); // 此处将直接输出纯文本内容
})
.fail(function() {
    alert("Error ");
});

方法2:提前发送响应终止渲染

如果需要跳过Yii2后续的所有渲染流程,可以手动发送响应后直接终止程序:

public function actionTest()
{
    $response = \Yii::$app->response;
    $response->format = \yii\web\Response::FORMAT_RAW;
    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->headers->set('Access-Control-Allow-Methods', '*');
    $response->content = 'My favourite color is red';
    $response->send();
    exit;
}

方法3:返回结构化数据推荐使用JSON格式

如果后续需要返回数组、对象等结构化数据,可以直接设置响应格式为JSON,Yii2会自动完成序列化:

public function actionTest()
{
    $this->layout = false;
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    \Yii::$app->response->headers->set('Access-Control-Allow-Origin', '*');
    // 直接返回数组即可,框架会自动转成JSON字符串
    return [
        'code' => 200,
        'message' => '请求成功',
        'content' => 'My favourite color is red'
    ];
}

前端可以添加dataType: 'json'配置,直接拿到解析后的JS对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:18:04