开发者

Using PHP methods in JS through JSON?

I have a PHP array of objects that have a function, getValue which gets the object's value. So, if i want to get it's value in PHP i just:

echo mapArray[2][2]->getValue;

I passed the array to JS using:

var mapArray = <?php echo json_encode($mapArray); ?>

If i do a

document.write(mapArray);

i get a whole array of "object Object" strings. If i try:

document.write(mapArray.[2][2].getValue);

i get "undefined".

Why this happens? Do i have to mimic PHP data object so the meth开发者_C百科ods are recognised in JS or the JSON encoding can give me a hand with this?


All json_encode does is return a string representing your data.

Imagine what it would take to be able to create JavaScript versions of all your PHP functions. json_encode would essentially have to be a compiler, able to understand all possible PHP functionality and convert it to equivalent JavaScript functionality.

It's possible to imagine such a thing working for simple functions, but how could it work for more elaborate code? If your getValue function invokes some of your library PHP code to make a MySQL connection, retrieve data, and perform calculations using built-in PHP functions that don't exist in JavaScript, the poor json_encode function would have to essentially convert the entire PHP language into JavaScript.

No, all you can get in JSON is data. Not functionality.

For the specific case you've described, where you have some private data with an accessor method, just create an array (or object) that describes the actual data you want returned to the browser before calling json_encode.


When you serialize the array to JSON and pass it to the client for evaluation with JavaScript you can only pass the representation of the array and it's contents (i.e. property values).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜