加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Cakephp3:如何返回json数据?

发布时间:2020-12-13 18:24:23 所属栏目:PHP教程 来源:网络整理
导读:我正在调用cakePhp控制器的ajax调用: $.ajax({ type: "POST",url: 'locations/add',data: { abbreviation: $(jqInputs[0]).val(),description: $(jqInputs[1]).val() },success: function (response) { if(response.status === "success") { // do somethin
我正在调用cakePhp控制器的ajax调用:
$.ajax({
                type: "POST",url: 'locations/add',data: {
                  abbreviation: $(jqInputs[0]).val(),description: $(jqInputs[1]).val()
                },success: function (response) {
                    if(response.status === "success") {
                        // do something with response.message or whatever other data on success
                        console.log('success');
                    } else if(response.status === "error") {
                        // do something with response.message or whatever other data on error
                        console.log('error');
                    }
                }
            });

当我尝试这个时,我收到以下错误消息:

Controller actions can only return CakeNetworkResponse or null.

在AppController中我有这个

$this->loadComponent('RequestHandler');

启用.

Controller函数如下所示:

public function add()
{
    $this->autoRender = false; // avoid to render view

    $location = $this->Locations->newEntity();
    if ($this->request->is('post')) {
        $location = $this->Locations->patchEntity($location,$this->request->data);
        if ($this->Locations->save($location)) {
            //$this->Flash->success(__('The location has been saved.'));
            //return $this->redirect(['action' => 'index']);
            return json_encode(array('result' => 'success'));
        } else {
            //$this->Flash->error(__('The location could not be saved. Please,try again.'));
            return json_encode(array('result' => 'error'));
        }
    }
    $this->set(compact('location'));
    $this->set('_serialize',['location']);
}

我在这里想念什么?是否需要其他设置?

我在这里看到的大多数答案要么过时,要么重载不必要的信息,要么依赖于withBody(),感觉解决方法而不是CakePHP方式.

以下是对我有用的东西:

$my_results = ['foo'=>'bar'];

$this->set([
    'my_response' => $my_results,'_serialize' => 'my_response',]);
$this->RequestHandler->renderAs($this,'json');

More info on RequestHandler.看起来它不会很快被弃用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读