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

如何解决多次调用Notification::build方法仅返回最后一次请求的问题

问题根因

  • 你当前每次调用build方法时,都会用新生成的通知代码覆盖session中notify键对应的旧值,因此多次调用后只会保留最后一次的内容,这是仅显示最后一条通知的原因。

调整方案

1. 修改build函数逻辑,改用数组存储多条通知

每次写入session前先读取已有的通知列表,将新通知追加到列表后再统一写入,避免覆盖旧内容:

public function build($title, $description, $type, $position, $closeTimeout, $showProgress)
{
    $notify = '<script>';
    $notify .= 'Notification.notify({';
    $notify .= 'title: "'.esc($title).'",';
    $notify .= 'description: "'.esc($description).'",';
    $notify .= 'image: {visible: true},';
    $notify .= 'type: "'.$type.'",';
    $notify .= 'position: "'.$position.'",';
    $notify .= 'closeTimeout: "'.$closeTimeout.'",';
    $notify .= 'showProgress: "'.$showProgress.'",';
    $notify .= '});</script>';
    // 读取已有通知列表,不存在则初始化空数组
    $notifyList = $this->Session->getFlashData("notify") ?: [];
    // 追加新通知到列表
    $notifyList[] = $notify;
    // 将通知列表写入session
    $this->Session->setFlashData("notify", $notifyList);
    return true;
}

2. 修改前端渲染代码,遍历输出所有通知

因为session中存储的已经是通知数组,需要循环输出每一项:

<?php if ($notifyList = session()->get('notify')) : ?>
    <?php foreach ($notifyList as $item): ?>
        <?= $item ?>
    <?php endforeach; ?>
<?php endif; ?>

调整完成后多次调用build方法生成的所有通知都会正常渲染生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:09:01