十月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>
部分尝试显示服务"变量和动态变量"变量:
in partial i try display "service" variable, and dynamic "variations" variable:
<h1>{{service.name}}</h1>
<span>Selected variation: variation[0].name</span>
它有效
组件: 但是如果我提出ajax请求,则变量"service"不会部分显示.为什么会这样呢?以及如何避免这种情况?
Component: but if I make a ajax request, variable "service" not display in partial. Why is this happening? And how to avoid this?
推荐答案
Ajax处理程序与十月份page life cycle
的工作方式不同.
Ajax handler is working differently from page life cycle
in October.
因此,当您调用页面时,它将使用所有数据和所有组件及其life-cycle
方法initialize page
.
so when you call page it will initialize page
with all the data and all components with its life-cycle
methods.
简而言之,所有数据均未在
ajax
请求中初始化
您希望service
对象位于部分内部,因此您正在使用
you want service
object inside partial so you are using
$this->page['service']
,但尚未初始化,因此将无法在ajax中使用
but its not been initialized so it will not available in ajax,
要使其在页面
code section
中可用,您需要使用onInit
方法.
to make it available in page
code section
you need to useonInit
method.
function onInit() {
$this['service'] = // your logic to get service and assign it;
}
现在此service
将在您的Ajax处理程序中提供
now this service
will available inside your ajax handler
公共函数onAjaxVariations(){ //$ this-> page ['service']将可用,并且可以传递给现在查看; }
public function onAjaxVariations() { // $this->page['service'] will be available and can be passed to view now; }
在正常页面刷新上工作,是因为所有page-cycle function executes
,所有component life-cycle
函数均已执行,因此$this->page['service']
将在此处可用.
on normal page refresh it works because all page-cycle function executes
, all component life-cycle
functions are executed so $this->page['service']
will be available here.
所有
component life-cycle
函数表示您的onRender
函数 => ,该函数调用prepareVars
=> ,该函数分配$this->page['service']
(这不是在Ajax调用中执行)
all
component life-cycle
functions means youronRender
function => which callsprepareVars
=> which assigns$this->page['service']
(this things are not executed in ajax call)
{更新首选解决方案}
如果您的代码取决于页面代码(页面生命周期)
简写代码写在页面
markup
内或code section
中,您想先执行它
in-short code is written inside page
markup
or incode section
and you want to execute it first
在您的ajax处理程序方法中,您可以使用此
inside your ajax handler method you can use this
$this->controller->pageCycle();
它将自动执行所有页面代码,并且所有变量现在都可用.
it will automatically execute all the page code and your all variable will be available now.
public function onAjaxVariations() {
$this->controller->pageCycle();
// $this->page['service'] will be available
}
这篇关于十月CMS. ajax请求后变量消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!