将类 stdClass 的对象转换为 JSON 对象

2022-08-30 23:10:58

这是我在php文件中的内容:

$session = $m->session;

$session现在是:

object(stdClass)[31]
  public 'id' => string '21112' (length=5)
  public 'external_id' => string '' (length=0)
  public 'sessiongroupid' => string '1843' (length=4)
  public 'eventid' => string '5588' (length=4)
  public 'order' => string '0' (length=1)
  public 'name' => string 'Ferdau Conference' (length=17)
  public 'description' => string 'Ferdau Conference' (length=17)
  public 'starttime' => string '2013-04-18 18:00:00' (length=19)
  public 'endtime' => string '2013-04-18 18:04:00' (length=19)
  public 'speaker' => string '' (length=0)
  public 'location' => string 'Waregem' (length=7)
  public 'mapid' => string '0' (length=1)
  public 'xpos' => string '0.000000' (length=8)
  public 'ypos' => string '0.000000' (length=8)
  public 'maptype' => string 'plan' (length=4)
  public 'imageurl' => string '' (length=0)
  public 'presentation' => string '' (length=0)
  public 'organizer' => string '0' (length=1)
  public 'twitter' => string '' (length=0)
  public 'allowAddToFavorites' => string '0' (length=1)
  public 'allowAddToAgenda' => string '0' (length=1)
  public 'votes' => string '0' (length=1)
  public 'url' => string 'http://ferdau.be' (length=16)
  public 'venueid' => string '0' (length=1)

我想将所有信息发送到我的javascript文件中名为save的函数。喜欢这个:

echo '<a onclick="save('.$session.')" style="cursor:pointer;" class="metacell">
                        <img src="'.buildUri("images/icons/favorite.png").'" width="16" />
                        <span>Add to favorites</span>
                    </a>';

当我尝试这样做时,我总是得到一个错误,只有一个字符串可以发送。如何将此对象转换为可以发送到我的javascript函数的内容?

我试过这个,没有结果:$data = json_encode($session);

当我这样做$data = json_encode((array)$session)

我得到这个:

<a class="metacell" style="cursor:pointer;" ferdau.be","venueid":"0"})"="" \="" 18:04:00","speaker":"","location":"waregem","mapid":"0","xpos":"0.000000","ypos":"0.000000","maptype":"plan","imageurl":"","presentation":"","organizer":"0","twitter":"","allowaddtofavorites":"0","allowaddtoagenda":"0","votes":"0","url":"http:\="" 18:00:00","endtime":"2013-04-18="" conference","starttime":"2013-04-18="" conference","description":"ferdau="" id":"21112","external_id":"","sessiongroupid":"1843","eventid":"5588","order":"0","name":"ferdau="" onclick="save({">

答案 1

$data = json_encode((array)$session);是正确的方法。

我猜你在那里显示的html是你在firebug /chrome开发工具/ IE开发工具中看到的。这就是浏览器尝试呈现它后的样子。尝试查看原始源代码,看看输出的实际情况。此时您的问题是由双引号引起的,因为双引号导致浏览器引擎认为在 的值结束之前关闭了属性。json_encodeonclick$data

您需要在HTML中混合转义双引号和/或使用单引号。我会从单引号开始,因为那会更简单。但是,您还必须确保其中的任何值都不包含未转义的单引号(因为这会导致相同的问题)。$data


答案 2