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'); } } }); 当我尝试这个时,我收到以下错误消息:
在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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |