脚本宝典收集整理的这篇文章主要介绍了Cakephp3:如何返回json数据?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
$.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']); }
以下是对我有用的东西:
$my_results = ['foo'=>'bar']; $this->set([ 'my_response' => $my_results,'_serialize' => 'my_response',]); $this->RequestHandler->renderAs($this,'json');
以上是脚本宝典为你收集整理的Cakephp3:如何返回json数据?全部内容,希望文章能够帮你解决Cakephp3:如何返回json数据?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。