如何在Laravel中无需刷新页面每分钟更新Blade foreach内的产品价格
实现无刷新自动更新产品价格的方案
步骤1:修改Blade模板,添加元素标识
给每个产品的价格标签加上带产品ID的自定义属性,方便后续JS定位对应元素更新值,修改后的循环代码如下:
@foreach ($products as $product ) <div class="product-item"> <span>{{$product->id}}</span> <span>{{$product->name}}</span> <!-- 给价格标签加data属性绑定产品ID --> <span class="product-price" data-pid="{{$product->id}}">{{$product->price}}</span> </div> @endforeach
步骤2:新增后端接口返回最新价格
在Laravel路由中新增一个接口,用于返回所有产品的ID和对应的最新价格,示例代码如下:
// 写在routes/web.php或者routes/api.php中均可 Route::get('/api/products/latest-prices', function () { // 只返回需要的ID和价格字段,减少传输体积 return \App\Models\Product::select('id', 'price') ->get() ->keyBy('id'); });
如果产品列表有权限限制,自行在路由中添加对应的权限验证中间件即可。
步骤3:添加前端定时更新逻辑
在Blade模板底部插入JS代码,实现每分钟拉取一次接口更新页面价格:
<script> document.addEventListener('DOMContentLoaded', function () { // 定义更新价格的公共方法 function refreshPrices() { fetch('/api/products/latest-prices') .then(res => res.json()) .then(latestPrices => { // 遍历页面所有价格标签更新值 document.querySelectorAll('.product-price').forEach(el => { const pid = el.dataset.pid; if (latestPrices[pid]) { el.textContent = latestPrices[pid].price; } }); }) .catch(e => console.error('价格更新失败:', e)); } // 页面加载完成先执行一次更新 refreshPrices(); // 每60秒执行一次更新 setInterval(refreshPrices, 60 * 1000); }); </script>
优化提示
如果产品数量较多,可以调整接口逻辑,只返回距离上次请求后价格发生变动的产品,进一步减少接口传输的数据量。如果后续需要更高的实时性,再考虑替换为WebSocket主动推送即可,当前每分钟更新的场景用定时拉取完全可以满足需求。
内容的提问来源于stack exchange,提问作者Mostafa Alavi
相关产品推荐
相关产品推荐

