thaJezath 的回答很好,但还有一些事情:
-
使用 CakePHP Js helper 处理所有 ajax 内容更简单、更 DRY:
<div id="output">
<?php
echo $this->Form->create();
echo $this->Form->input('input1');
echo $this->Form->input('input2');
echo $this->Js->submit('submit',array('update' => '#output');
?>
</div>
这将自动添加为您处理 ajax 提交的缓冲脚本。但是您需要在布局中的 echo $this->Js->writeBuffer(); 行,就在 </body> 标签之前。
但这仍然返回<div id="output">... - 如果您将更改为'update' => '#content',它将重新加载整个内容div。
- 如果您确实需要更新表单而不是其他内容:
在您的视图文件中:
<div id="output">
<?php $this->start('ajax-content'); // this line starts new block ?>
<?php
echo $this->Form->create();
echo $this->Form->input('input1');
echo $this->Form->input('input2');
echo $this->Js->submit('submit',array('update' => '#output');
?>
<?php
$this->end(); // this line ends block
echo $this->fetch('ajax-content'); // this line print contents of block
?>
</div>
在您的 /View/Layouts/ajax.ctp 中:
<?php
// next 2 lines only ensure that ajax-content block exists
// if not it will be just empty string
$this->startIfEmpty('ajax-content');
$this->end();
echo $this->fetch('ajax-content'); // this line outputs ajax-content block (the form)
?>
因此,总而言之,此方法将您想要返回的内容包含在视图块内的 ajax 内容中。然后 ajax 布局而不是打印整个视图 ($this->fetch('content');) 它只打印 ajax-content 块的内容 ($this->fetch('ajax-content');)。这样您就可以在每个视图中标记您希望在 ajax 请求期间返回的所有内容。
线条:
$this->end(); // this line ends block
echo $this->fetch('ajax-content'); // this line print contents of block
可能不太方便 - 最好将所有块记录代码放在您自己的助手中以便简单地使用它:
<div id=...
$this->AjaxContent->start();
your form here
$this->AjaxContent->stop();
</div>
正如 thaJezath 在 cmets 中所写,JsHelper 将在未来的版本中被弃用,因此如他所说,使用视图块会更安全。 HtmlHelper 有方便的方法:
<?php $this->Html->scriptStart(array('inline' => false)); ?>
$(document).ready(function(){
// your code here
});
<?php $this->Html->scriptStart(array('inline' => false)); ?>
这会将您的脚本添加到由$this->fetch('script');以默认布局打印的viewBlock "script"