문제

This is killing me. I'm using JQuery 1.10.2 and Cakephp 2.2 and I want to do a GET from javascript. This is my code:

Javascript:

  var arg='/sites/fechas/10-02-2013';
  $.get(arg, function(data) {
     console.log(":" + data);
  }); 

CakePHP code (SitesController.php):

  public function fechas($fecha_reserva) {
     $this->autoRender = false;
     $fechas = $this->Informacion->find('count', array(
        'conditions' => array(
           'Informacion.fechas' => str_replace('-', '/', $fecha_reserva))
     ));
     return json_encode($fechas);
  }   

From chrome developer tools

Request URL:http://my.web.com/sites/fechas/10-02-2013
Request Headers view parsed
GET http://my.web.com/sites/fechas/10-02-2013 HTTP/1.1
Accept: */*
Referer: http://my.web.com/reserva
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)       Chrome/29.0.1547.62 Safari/537.36

If I write the url in the browser I get a response (just a number). But from javascript I get nothing.

도움이 되었습니까?

해결책

Use a view. Don't return directly from the Controller. You can either:

  • Use data views (from cake > 2)
  • render an empty view in an empty layout

The data views approach is very good however you will need todo some setup as described in the link - parseExtensions, add the RequestHandlerComponent, etc. It is cleaner than the second option. Check the documentation and decide which one is for you. The second option is the "old way to do it". Anyway if you want to do it the by the second way this is what you need to do:

  • Create an ajax.ctp layout file under View/Layouts. Can be called whatever you like
  • Have ONLY the content_for_layout display in it: <?php echo $content_for_layout; ?>
  • Create a view: <?php echo json_encode($fechas);?>
  • Include the RequestHandler component if you are not getting the right headers
  • In your controller after you get the data:

    $this->set('fetchas', $fechas);

    $this->render('your_view's_name_here')

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top