开发者

Passing a PHP Object as argument of a javascript function

My searching skills seems to have failed me. I have this php object that I unserialize from a mysql entry, and I want to pass it as an argument to a javascript function, so it could compare the object with the values in a form. From what I gathered from my s开发者_Python百科earch, encoding the object as a json object would have done the trick, but when I'm doing a json_encode on the variable, it only result in {}.

Here is the relevant snippet of code:

<?php
$data = new Data();
$data = unserialize(base64_decode($rawdata));//Where $rawdata is the data retrieved from the mysql query.
/* using function such as $data->getName() to retrieve the relevant data */
?>

<form id="myform" action="#" method="post" onsubmit="compareEntry(<?=json_encode($data)?>)">

<!-- Different input and select field initialized with the php data -->

<input type="submit" onclick="compareEntry(<?=json_encode($data)?>)"/>
</form>
<!--<?=json_encode($data)?>--> 

I know that the php data is correctly retrieved from the database, as the values in the form are all correctly initialized. Only with the last html comment did I knew that I had an empty json object.

Here is an example of what print_r($data) returns (sensitive information edited):

(
    [m_path:private] => 
    [m_version:private] => REL_54
    [m_bugs:private] => Array
 *RECURSION*
    [m_targets:private] => Array
 *RECURSION*
    [m_symptoms:private] => Array
 *RECURSION*
    [m_exception:private] => Array
 *RECURSION*
    [m_instruction:private] => Array
 *RECURSION*
    [m_sources:private] => Array
 *RECURSION*
    [m_risks:private] => Array
 *RECURSION*
    [m_test:private] => Array
 *RECURSION*
    [m_contact:private] => Array
 *RECURSION*
)
1

Do I do something wrong? Is encoding to JSON the right approach in my scenario?


JSON is the correct way to do it. And basically json_encode/json_decode works well in that case. If it returns an empty object maybe there is a problem with the data you are trying to encode. the function expects the data to be in UTF-8, while PHP itself is still ISO-8859-1. So if you have e.g. special characters in some fields it may help if you convert these first with utf8_encode.


Your object contains private properties only that won't be output by json_encode.

Also, there seems to be some sort of recursion going on, probably meaning that a member of each array is referencing the object itself (or something like that).

You will need to make some of the properties public, and probably also fix the recursion issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜