2016-12-08 9 views
2

Я имею Аякс после вызова к контроллеру CakePHP: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'); 
        } 
       } 
      }); 

Когда я пытаюсь это, я получаю следующее сообщение об ошибке:

действие контроллера может возвращать только торт \ Network \ Response или нуль ,

В AppController я это

$this->loadComponent('RequestHandler'); 

включен.

функция контроллера выглядит следующим образом:

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']); 
} 

Что мне не хватает здесь? Нужны ли дополнительные настройки?

+1

'Co Действия ntroller могут только возвращать Cake \ Network \ Response или null. 'Что так непонятно об этом сообщении об ошибке? Очевидно, вы возвращаете строку 'return json_encode()'. – burzum

+0

Извините, я до сих пор не понимаю смысла? Я возвращаю массив, как в примере выше? – user1555112

+1

У вас нет. http://php.net/manual/en/function.json-encode.php И вы когда-нибудь читали это? http://book.cakephp.org/3.0/ru/views/json-and-xml-views.html – burzum

ответ

5

Вместо того, чтобы возвращать результат json_encode, установите тело ответа с этим результатом и верните его обратно.

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']); 
      $resultJ = json_encode(array('result' => 'success')); 
      $this->response->type('json'); 
      $this->response->body($resultJ); 
      return $this->response; 
     } else { 
      //$this->Flash->error(__('The location could not be saved. Please, try again.')); 
      $resultJ = json_encode(array('result' => 'error', 'errors' => $location->errors())); 

      $this->response->type('json'); 
      $this->response->body($resultJ); 
      return $this->response; 
     } 
    } 
    $this->set(compact('location')); 
    $this->set('_serialize', ['location']); 
} 
+0

Это: $ this-> response-> type ('json'); и $ this-> response-> body ($ resultJ); помогло мне много, спасибо! – user1555112

+0

Я обновил anwser, чтобы включить ошибки проверки. –

+0

Для преополя, который преуменьшает, я высоко ценю, если вы объясните мне, что не так в anwser. Это то, что действительно поможет (не только вниз) - СПАСИБО –

5

Есть несколько вещей, чтобы вернуть JSON ответ:

  1. нагрузки RequestHandler компонента
  2. установленного режим рендеринга, как json
  3. набор типа контента
  4. набора необходимых данных
  5. определяют _serialize значение

, например, вы можете перемещать первые 3 шага к каким-либо способом в родительском классе контроллера:

protected function setJsonResponse(){ 
    $this->loadComponent('RequestHandler'); 
    $this->RequestHandler->renderAs($this, 'json'); 
    $this->response->type('application/json'); 
} 

позже в вашем контроллере вы должны вызвать этот метод, и набор необходимых данных;

if ($this->request->is('post')) { 
    $location = $this->Locations->patchEntity($location, $this->request->data); 

    $success = $this->Locations->save($location); 

    $result = [ 'result' => $success ? 'success' : 'error' ]; 

    $this->setJsonResponse(); 
    $this->set(['result' => $result, '_serialize' => 'result']); 
} 

также похоже, что вы также должны проверить на request->is('ajax); Я не уверен в возвращении json в случае запроса GET, поэтому метод setJsonResponse вызывается в пределах if-post блока;

в вашем Ajax вызова обработчика успеха вы должны проверить result значение поля:

success: function (response) { 
      if(response.result == "success") { 
       console.log('success'); 
      } 
      else if(response.result === "error") { 
        console.log('error'); 
      } 
     } 
+0

, что один из них - удобный ответ! БРАВО –

0

При возврате данных JSON необходимо определить тип данных и информации тела ответа, как показано ниже:

$cardInformation = json_encode($cardData); 
$this->response->type('json'); 
$this->response->body($cardInformation); 
return $this->response; 

В случае вам просто изменить эту return json_encode(array('result' => 'success')); линию ниже код:

$responseResult = json_encode(array('result' => 'success')); 
$this->response->type('json'); 
$this->response->body($responseResult); 
return $this->response;