我强烈建议不要编写文件,而是建议使用Requirements::customScript()
是的,如果你把它放在它不会被调用的地方(在 DataObject 中)那将是无用的 所以让我们把它放在有意义的地方,例如 Page_Controller->init(),
当然我们需要获取 SliderSettings 对象,这可以通过 SliderSettings::get()->First() 来完成,这给了你数据库中的第一个 SliderSettings 对象,如果你想得到一个特定的,你也可以通过 ID 得到它:SliderSettings::get ()->按ID(42)
class Page_Controller extends ContentController {
public function init() {
parent::init();
$sliderSettings = SliderSettings::get()->First();
if ($sliderSettings) {
$sliderSettings = Convert::array2json(array(
'SliderEffect' => $sliderSettings->SliderEffect,
'SliderCaptions' => $sliderSettings->SliderCaptions,
'SliderRandom' => $sliderSettings->SliderRandom,
'SliderTicker' => $sliderSettings->SliderTicker,
'SliderPager' => $sliderSettings->SliderPager,
'SliderControls' => $sliderSettings->SliderControls,
'SliderStart' => $sliderSettings->SliderStart,
'SliderAdaptive' => $sliderSettings->SliderAdaptive,
'SliderSpeed' => $sliderSettings->SliderSpeed,
'SliderPause' => $sliderSettings->SliderPause,
));
Requirements::customScript("var sliderSettings = $sliderSettings;");
// Requirements::customScript will put it at the bottom of the HTML, if you need it above the other JS files, you can put it into the header with the following workaround/hack: (if you use this, remove the Requirements::customScript line)
// Requirements::insertHeadTags("<script type='text/javascript'>var sliderSettings = $sliderSettings;</script>");
}
}
}
就是这样,现在你应该sliderSettings
在javascript中有一个名为availiable的变量。这个变量是一个对象,
所以你可以像这样sliderSettings.SliderEffect
访问sliderSettings['SliderEffect']
它:$(document).ready(function() {})