简体   繁体   中英

Saving data in CakePHP, and posting JSON via AJAX simultaneously?

So I have a form, AND I have a KnockoutJs app, with a CakePHP back end. When I hit Cake's default "save" button, I'm wanting to spit out and post a JSON along with the standard form data.

Here's what I have in my JS so far:

$('input.saveProgram').click(function() {
    var theJson = ko.mapping.toJSON(pvm, mapping);
    $.ajax({
        url: 'http://localhost/cake/programs/edit',
        dataType: 'json',
        type: 'POST',
        data: theJson
    });
});

In Cake, I'm trying to use the the Request handler in my controller, but to no avail:

if($this->RequestHandler->setContent('json', 'application/json')) {
    // standard saving code
}

In my Cake app I've tried die($this->request->data) to see what's going on and the JSON doesn't seem to be posting at all.

Here's a solution as I interpret your question. In your controller:

    if($this->RequestHandler->isAjax()){

        // "spit" out json
        echo $this->data;

        //decode data into an array
        $decodedData = json_decode($this->data);        

        //standard saving code would 
        $this->Model->save($decodedData);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM