将JSON数据从PHP返回给AJAX

5
我正在尝试从php中获取json对象,以便在ajax中使用。以下是我的ajax代码:
 $.ajax({
   type: 'get',
   url: eventsListPath,
   dataType : "json",
   data: {},
   success: function (data) {
       $('#eventInformation').html(data.table);
       alert(data.table);
   }
});

我的PHP代码:

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

但是这条线

alert(data.table);

返回'undefined',有什么想法吗?


success 中尝试使用 console.log(data)。告诉我结果。 - iplus26
4个回答

1
在您的 PHP 代码中尝试这个。对一个数组进行 JSON 编码。
$obj['table']="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);

替代方案 - 或者你的类应该像这样
class your_classname
{
  public $table;
 //other class related code
}
$obj = new your_classname;

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

如果这段代码对您有帮助,请标记我的答案为正确的,感谢@Steven Jacks - Harish Lalwani

1
如果我没记错的话,json_encode只适用于数组。
$obj = [{table:"hey"}];

0
<?php
$obj = new stdClass();
$obj->table="hey";
echo json_encode($obj)

生成

{"table":"嘿"}

使用Firebug进行检查。还要检查内容类型,应为Content-Type: application/json


0

你必须传递数组给json_encode而不是对象

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接