十月 CMS。 ajax 请求后变量消失

OctoberCMS. Variable disappears after ajax request

我的组件模板代码:

default.htm:

<div id="filter_variations" style="//display: none;">
{{ form_ajax('onAjaxVariations') }}
    <input type="text" id="var_id" name="Filter[id]" value="">
    <input type="submit">
{{ form_close() }}
</div>
<div id="partial_service">
    {% partial __SELF__ ~ '::service' %}
</div>

在部分我尝试显示 "service" 变量和动态 "variations" 变量:

<h1>{{service.name}}</h1>
<span>Selected variation: variation[0].name</span>

有效

分量: 但是如果我发出 ajax 请求,变量 "service" 不会部分显示。为什么会这样?以及如何避免这种情况?

Ajax 处理程序的工作方式与 10 月份的 page life cycle 不同。

因此,当您调用页面时,它将 initialize page 包含所有数据和所有组件及其 life-cycle 方法。

in-short all data is not initialized in ajax request

你想要 service object inside partial 所以你正在使用

$this->page['service']

但尚未初始化,因此在 ajax、

中不可用

to make it available in page code section you need to use onInit method.

function onInit() {
    $this['service'] = // your logic to get service and assign it;
}

现在这个 service 将在您的 ajax 处理程序中可用

public 函数 onAjaxVariations() { // $this->page['service'] 将可用并可以传递给现在查看; }

在正常页面刷新时它可以工作,因为所有 page-cycle function executes、所有 component life-cycle 功能都已执行,因此 $this->page['service'] 将在此处可用。

all component life-cycle functions means your onRender function => which calls prepareVars => which assigns $this->page['service'] (this things are not executed in ajax call)

{ 更新首选解决方案 }

如果你的代码依赖于页面代码(page lifeCycle)

in-short code is written inside page markup or in code section and you want to execute it first

inside your ajax handler method you can use this

$this->controller->pageCycle();

它会自动执行所有页面代码,您的所有变量现在就可用了。

public function onAjaxVariations() {
    $this->controller->pageCycle();
    // $this->page['service'] will be available
}