我想使用 JSON 对对象进行编码以响应 AJAX 请求。首先,我将对象转换为数组(结果看起来不错),然后使用 json_encode
将数组编码为 JSON 格式,但我得到了意外的结果。获取的 JSON 字符串在属性名称之前具有类名,并且空字符"''0000"出现在许多位置。我的所有文件都使用 UTF-8 进行编码。如果我使用 get_object_vars
,我得到的结果array = []
。
如何解决此问题?
我得到的结果:{"'u0000DB'u0000connection":null,"'u0000DB'u0000serverName":"localhost","'u0000DB'u0000userName":"root","'u0000DB'u0000password":null,"'u0000DB'u0000dbName":"thahtin"}
这是我使用的代码:
class DB
{
private $connection;
private $serverName;
private $userName;
private $password;
private $dbName;
public function __construct()
{
$config = new Configuration();
$this->serverName = 'localhost'; //$config->getConfig("server");
$this->userName = 'root'; //$config->getConfig("userName");
$this->password = null; //$config->getConfig("password");
$this->dbName = 'thahtin'; //$config->getConfig("database");
}
public function open()
{
if(!$this->connection)
mysql_close($this->connection);
$this->connection = mysql_connect($this->serverName, $this->userName, $this->password);
if(!$this->connection)
{
die('Could not connect. Error: ' . mysql_error());
}
mysql_select_db($dbName);
}
}
$db = new DB();
echo json_encode((array)$db);
get_object_vars
返回一个空数组,因为所有属性都是私有的。将它们公开,或者(更好的是)自己构造数组,以便您可以控制其中的内容。