【问题标题】:OctoberCMS pass variable onStart to AJAX functionOctoberCMS 将变量 onStart 传递给 AJAX 函数
【发布时间】:2022-01-07 17:04:07
【问题描述】:

我的主页面包含以下代码:

function onStart()
{
  // ...
  // $result => Response of an API
  $this['prices'] = $prices;
}

function onAjax()
{
  // ...
  // $result => Response of another API
  $this['products'] = $products;
}

我的 AJAX 部分是:


{% for product in products %}

<div id="price">
  {{ prices[product.name] }}
</div>

{% endfor %}

但它无法读取prices 变量。我怎样才能通过?

【问题讨论】:

  • 您好,您使用的是哪个版本的 OctoberCMS?基于此,我们可以正确指导您..

标签: octobercms


【解决方案1】:

您可以简单地推送部分数据来更新部分。

参考:https://tutorialmeta.com/octobercms/october-cms-update-partial-using-ajax-framewrok

1.创建需要在the theme's partial's directory 中更新的partial。我们就叫它product-list.htm


<!-- here you can put condition if there is no product or there is no prices do not render anything and show message etc... -->
{% if products|length != 0 and prices|length != 0 %}
  {% for product in products %}
    <div id="price">
      {{ prices[product.name] }}
    </div>
  {% endfor %}
{% else %}
  <p>Please fetch from ajax</p>
{% endif %}

2。现在您需要在代码中使用该部分。在您的主页上。


在你的代码部分,你可以这样使用它。

function prepareVars() {
  // ...
  // $products => Response of another API
  // $prices => Response of another API


  // these are the variable will be available in the partial/page
  $this['prices'] = $prices;
  $this['products'] = $products;
}

function onStart()
{
  $this->prepareVars();
}

function onAjax()
{
  $this->prepareVars();
  return ['#partialId' => $this->renderPartial('product-list')];
}

在你的标记部分,你可以像这样使用它。

<div id="partialId">
 {% partial 'product-list' products=products %}
</div>

<button class="btn btn btn-primary" data-request="onAjax">
  Start Ajax
</button>

它将如何运作?


  1. 最初页面加载onStart 将被调用,然后您获取产品或其他一些东西。并直接传递给部分并根据需要渲染该部分。

  2. 加载页面后,单击Start Ajax 按钮并拨打ajax call,此调用将调用onAjax

  3. onAjax 处理程序将处理请求并获取 prices 并使用传递的数据 ($this['variable_name']) 再次呈现部分。

  4. 现在它将准备部分,然后我们将其推送到所需的 ID ('#partialId'),这样我们就可以更新我们的部分。

如有任何疑问,请发表评论。

【讨论】:

    【解决方案2】:

    这是因为 onStart() 只在页面创建时运行一次。您可以了解this here。它声明:“onStart 函数在页面执行开始时执行。”

    要将价格加载到部分中,您应该将onStart() 函数放入部分代码部分而不是页面。

    function onStart()
    {
      // ...
      // $result => Response of an API
      $this['prices'] = $prices;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 2023-04-03
      • 2016-04-10
      • 2019-04-21
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多