Cakephp, jquery, .ajax (), dataType: json

Is it possible to get by without presenting the cakephp controller function? I am trying to get my server to return a data type that is not a string, but an array

my controller function:


    function test() {
      $this->layout = 'plain';
      $task['Numbers']['uno'] = 'mooo';
      $task['Numbers']['dos'] = 'says the cow';
      $result = json_encode($task);
      $this->set('result', $result);
    }

my view file is test.ctp



    echo $result;


my jquery:



    $('#test').live('click', test);

    function test() {

        var data = $('#form').serialize();

        $.ajax({
        type: "post",
        url: "/controller/test",
        data: data,
        dataType: 'json',
        success: function(response){            
        alert(response.Numbers.uno);
        }
        });

    }

clicking on the html element marked test doesn't give me anything. however if i take out

dataType: 'json', 

and change
alert(response.Numbers.uno);
to
alert(response);

in my jquery - i get an alert: the json encoded data but as a string (
alert(typeof response);
)

does anyone have any idea what might be happening?

+3
source share
5 answers

-, , , ( ). (test, ) $this->autoRender = false;. , , JSON . .

, , - config.php. 0, , . echo- JSON, . Configure::write ( 'debug', 0 ). . AppController:

if ( $this->RequestHandler->isAjax() ) {
   Configure::write ( 'debug', 0 );
}

, Firebug, , ajax-. . . , Firebug , .

+3

, , . , , - . , .

Configure::write('debug', 0);
$this->autoRender = false;

firebug. firebug , , firebug, , . , jquery .

+1

.
. :

jQuery ajax- json, ?

var json = $.parseJSON(response);
alert(json.Numbers.uno);
0

die(json_encode(array('success' => true, 'result' => $result)));

, .

0

Source: https://habr.com/ru/post/1714458/


All Articles