在CakePHP的默认情况下,Controller中的action都要求有一个对应的view视图。而处理Ajax请求的action则不需要视图,这里有两种处理方式:
1、在action开头调用render()方法
$this->render(false);
2、在action最后执行 exit();
注意此时如果action有返回值,要使用 echo
而不是 return
,如 echo json_encode(['Foo' => 'bar'])
。
以上方式虽然可以实现Ajax请求的效果,但并不是最佳实践,根据CakePHP的官方说明,Controller actions can only return Cake\Http\Response or null。可见,在处理Ajax请求的action中应该返回包含自定义数据的Cake\Http\Response对象。
在View层使用jQuery发出Ajax请求:
$.ajax({
type: "POST",
url: "<?= $this->Url->build(['controller'=>'Users', 'action'=>'resetPwt']) ?>",
data: {userId: '1'},
dataType: 'json',
success: function(data) {
console.log("Reset user#"+data.userId+"'s password successfully.");
}
});
在Controller中处理该请求:
public function resetPwt() {
if($this->request->is('ajax')) { //判断是否为Ajax请求
$userId = $this->request->getData('userId'); //获取请求参数
$this->response = $this->response->withType('application/json') //设置响应类型
->withStringBody(json_encode(['userId' => $userId])); //设置响应数据
}
return $this->response; //返回Cake\Http\Response对象
}