How to return the correct content-type for JSON in CakePHP?

前端 未结 5 543
别那么骄傲
别那么骄傲 2021-02-04 13:24

I\'m trying to set the content-type header for a JSON response accessed with an AJAX GET request. I\'ve followed tutorials on blogs and the bakery but I always receive \'text/ht

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 14:13

    I make Ajax calls to retrieve JSON content in all of my projects and I've never done most of what you're doing here. The extent of my controller code looks something like this:

    public function do_something_ajaxy() {
      Configure::write ( 'debug', 0 );
      $this->autoRender = false;
    
      /** Business logic as required */
    
      echo json_encode ( $whatever_should_be_encoded );
    }
    

    I make my Ajax calls via jQuery so I suppose that could make a difference, but it would surprise me. In this case, you're problem appears to be in the handler, not with the caller. I'd recommend removing lines 17-23 and replacing them with a simple echo json_encode ( array('response' => $actions[0]) ) statement.

    You're also testing for $this->RequestHandler->isGet(). Try testing $this->RequestHandler->isAjax() instead. I'm not sure whether Ajax calls are recognized as by both their type and their method.

提交回复
热议问题