LoginSignup
1
3

More than 5 years have passed since last update.

[ZF3] AjaxリクエストをZend Framework 3でレスポンスする

Last updated at Posted at 2017-05-09
  1. module.config.phpを設定する
  2. JsonModelを使用して返却する

module.config.phpを設定する

'view_manager' =>
    'strategies' => 'ViewJsonStrategy' // この部分

JSONペイロードをレスポンスできるように設定に追加します。
この設定がないと下記の処理でJSONがレスポンスされません。

JsonModelを使用して返却する

IndexController.php

use Zend\View\Model\JsonModel; // namespace

public function indexAction()
{
    return new ViewModel();
}

public function ajaxAction()
{
    // $data = $this->getRequest->getQuery(); // GET
    // $data = $this->getRequest->getPost(); // POST
    $data = array(
        'message' => 'Hello World!!',
    );
    return new JsonModel($data);
    // namespaceを使用しない場合は
    // return new \Zend\View\Model\JsonModel($data)
}

[URL Path] /application/ajax

  • /{controller}/{action}
  • IndexControllerはapplicationとしてコントローラ設定されています

備考

ログ出力

private function __log ()
{
    $stream = @fopen('/var/www/html/zend/data/logs/debug_log.txt', 'a', false);
    if (!$stream) {
        throw new Exception("Can't open stream.");
    }
//        $stream = 'php://output';
    // 適宜 namespace を使用
    $writer = new \Zend\Log\Writer\Stream($stream);
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);

    $param = $this->getRequest()->getPost();

    $logger->debug(var_export($param, true));
}

Ajax sample
[jQuery] AjaxでPHPにPOST送信する

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3