Php 如何在同一操作中处理表单呈现和ajax响应?
我的ProjectsController中有Php 如何在同一操作中处理表单呈现和ajax响应?,php,ajax,cakephp,cakephp-2.0,Php,Ajax,Cakephp,Cakephp 2.0,我的ProjectsController中有create()方法,该方法使用AJAX呈现表单并保存其数据: class ProjectsController extends AppController { public function create() { if ($this->request->is('post')) { $this->Project->create();
create()
方法,该方法使用AJAX呈现表单并保存其数据:
class ProjectsController extends AppController
{
public function create()
{
if ($this->request->is('post'))
{
$this->Project->create();
$this->request->data['Project']['created_by'] = $this->Auth->user('id');
if ($this->Project->save($this->request->data))
{
...
} else {
...
}
}
}
如果数据已保存,我如何传递成功消息?如果表单不是ajax请求,我如何呈现表单?我无法设置autoRender
false'因为它必须呈现表单
这是处理jax请求的最正确方法吗?如果没有,我该怎么办?检测AJAX: 您可以使用:
if($this->request->is('ajax')) {
用ajax做任何你想做的事情,剩下的就用“else”来做
处理它:
可能是这样的:
if ($this->request->is('ajax')) {
//process the ajax response
$this->render('/Ajax/json');
} else {
if($this->request->is('post')) {
//process the post
}
//set variables for the view...etc etc
}
另一个选项-单独的功能:
或者,有两种不同的操作也是很常见的——一种用于ajax,另一种用于您想要的任何其他操作。这是我喜欢的方式,因为我不希望到处都有if()块。但是,每个人都有自己的,我看到他们都经常使用
public function create_ajax() { ... }
public function create() { ... }
检测AJAX: 您可以使用:
if($this->request->is('ajax')) {
用ajax做任何你想做的事情,剩下的就用“else”来做
处理它:
可能是这样的:
if ($this->request->is('ajax')) {
//process the ajax response
$this->render('/Ajax/json');
} else {
if($this->request->is('post')) {
//process the post
}
//set variables for the view...etc etc
}
另一个选项-单独的功能:
或者,有两种不同的操作也是很常见的——一种用于ajax,另一种用于您想要的任何其他操作。这是我喜欢的方式,因为我不希望到处都有if()块。但是,每个人都有自己的,我看到他们都经常使用
public function create_ajax() { ... }
public function create() { ... }
我将使用post参数指示请求是ajax,我将使用post参数指示请求是ajax。