简体   繁体   中英

Retrieving JSON data in controller from URL with cakephp

I'm trying to pass JSON encoded data from Knockout.js to an action in my controller but it's not working and showing as null.

I used the same script in a non-cake php file and it worked perfectly. Is there a special way to decode json data with cake? Say this is the URL being passed.

/orders/submit_order/%7B"orderInfo":["itemNumber":"1","quantity":"1","price":"1.00","productName":"Test Product"]%7D

Here is the action

//OrdersController

function submit_order($order = null){
    $order = json_decode($order, true); 
    print_r($order);
   //I also tried commenting out the json decode to simply pass the info without further processing but that just displayed "t"

}

Is there a special way to handle this with Cakephp? With a standard php file I'd set something like

 page.php?order=....json data

And then access it with

$order = $_GET['order'];

Perhaps try sending the data via POST instead of GET? It is possible that the array notation in the url is not being escaped correctly.

Have you tried sending the data as a regular query string and then accessing it as your would any normal string in your controller?

Check out jQuery.param() which should allow you to turn a json object into a query string. Here is the example from the page:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));

alert(recursiveEncoded);
alert(recursiveDecoded);

and the results (respectively for each function called):

a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3 
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

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