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

如何在October CMS中通过Ajax传递经过过滤的集合?

October CMS 产品过滤页面与组件实现示例

页面配置与模板代码

这是你的产品过滤页面代码,它整合了AJAX表单、局部视图和自定义组件调用,实现了无刷新的产品筛选功能:

title = "products"
url = "/filter-products/:category_slug?"
layout = "default"
is_hidden = 00
[filterproducts]
==
{{ form_ajax('onFilterProducts', { update: {'product/products-listing': '#partialProducts'} }) }}
    {% partial 'products-filters' %}
{{ form_close() }}
<table id="partialProducts">
    {% partial 'product/products-listing' products = filterproducts.products %}
</table>

关键逻辑说明

  • 页面URL设置了可选路由参数 :category_slug?,支持通过分类别名直接预过滤产品
  • 调用自定义的 filterproducts 组件来处理核心的产品筛选逻辑
  • 使用 form_ajax 提交筛选表单,通过AJAX更新 #partialProducts 容器内容,避免整页刷新
  • 筛选表单的UI封装在 products-filters 局部视图中,产品列表则渲染在 product/products-listing 局部视图里

自定义组件代码结构

你的 FilterProducts 组件需要基于October CMS的组件基类扩展,基本实现结构如下:

<?php

namespace YourNamespace\PluginName\Components;

use Cms\Classes\ComponentBase;
use YourNamespace\PluginName\Models\Product;

class FilterProducts extends ComponentBase
{
    public $products;

    public function componentDetails()
    {
        return [
            'name'        => '产品筛选组件',
            'description' => '处理产品的分类筛选和AJAX过滤逻辑'
        ];
    }

    public function defineProperties()
    {
        return [
            // 可在这里定义组件的可配置属性,比如默认产品显示数量、排序方式等
        ];
    }

    public function onRun()
    {
        // 页面初始化时,根据路由参数加载对应分类的产品
        $categorySlug = $this->param('category_slug');
        $this->products = $this->getFilteredProducts($categorySlug);
    }

    public function onFilterProducts()
    {
        // 处理AJAX筛选请求,获取表单提交的筛选参数
        $filters = post();
        $categorySlug = $this->param('category_slug');
        $this->products = $this->getFilteredProducts($categorySlug, $filters);
        
        // 返回更新后的产品列表局部视图
        return $this->renderPartial('product/products-listing', [
            'products' => $this->products
        ]);
    }

    protected function getFilteredProducts($categorySlug = null, $filters = [])
    {
        // 实现具体的产品筛选逻辑,可根据需求扩展更多筛选条件
        $query = Product::query();
        
        if ($categorySlug) {
            $query->whereHas('category', function($q) use ($categorySlug) {
                $q->where('slug', $categorySlug);
            });
        }

        // 示例:处理价格区间筛选
        if (!empty($filters['price_min'])) {
            $query->where('price', '>=', $filters['price_min']);
        }
        if (!empty($filters['price_max'])) {
            $query->where('price', '<=', $filters['price_max']);
        }

        return $query->get();
    }
}

注意要点

  • 确保组件的命名空间和模型路径与你的插件结构完全匹配
  • onFilterProducts 方法名要和表单中指定的AJAX动作名完全一致
  • 局部视图的路径要对应项目中实际的文件位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:15