简体   繁体   中英

return a PHP object to an ajax call

I'm learning PHP OOP, and getting used to all of these objects.

When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back. But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP?

Thanks a lot for your answers Romain

Example:

On the client side

$.ajax(
{
  url:"test.php",
  type:"POST",
  dataType:"json",
  success:function(json)
  {
    // json into template
  }
});

On the server side : test.php

require_once("bdd.php");

function loadClass($class)
{
    require $class.".class.php";
}

spl_autoload_register('loadClass');

$PersonneM = new PersonneManager($db);

$perso = $PersonneM->get("123456");

$perso = serialize($perso); // ????????????

header('Content-type: application/json');
echo json_encode(array("result",$perso));

either use serialize or __toString to create a JSON-representation of your data that you can send down the tube. You will not be needing an extra array around your object.

However, there is an error in some JSON parsers/interpreters that can mess with your data when not wrapped in an array. But I haven't heared anything of this issue since a couple of years so you should be safe

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