简体   繁体   中英

Returning json data from php to ajax

I'm trying to get a json object from php so I can work with it in ajax. Here is my ajax code:

 $.ajax({
   type: 'get',
   url: eventsListPath,
   dataType : "json",
   data: {},
   success: function (data) {
       $('#eventInformation').html(data.table);
       alert(data.table);
   }
});

And my PHP:

$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

But the line

alert(data.table);

comes back with 'undefined'. Any ideas?

Try this in your php code. Json encode an array.

$obj['table']="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

Alternate - Or your class should be like this

class your_classname
{
  public $table;
 //other class related code
}
$obj = new your_classname;

$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

如果我没弄错的话,json_encode只适用于数组

$obj = [{table:"hey"}];
<?php
$obj = new stdClass();
$obj->table="hey";
echo json_encode($obj)

produces

{"table":"hey"}

Check it using Firebug. Also check the content-type, should be Content-Type: application/json

you must pass array to json_encode not object

<?php
$array['table'] = "hey";
echo json_encode($array, JSON_UNESCAPED_SLASHES);

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