如何在CakePHP中使用Ajax请求

在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对象
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

般若Neo

交个朋友,请作者喝杯咖啡~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值