开发者

pass multidimentional array from javascript to php

开发者 https://www.devze.com 2022-12-12 22:11 出处:网络
Im running a javascript code which reads values from different XML files and it generates a multidimentional array based on those values. Now I need to pass this array to a PHP page. I tried different

Im running a javascript code which reads values from different XML files and it generates a multidimentional array based on those values. Now I need to pass this array to a PHP page. I tried different but it always pass the arrray as string not as an array. Anyone has an开发者_如何学C idea :( ... and thank you very much


What Caleb said. Use this and JSON encode your JS array to a string, send it over to PHP and use json_decode to decode it into a PHP array.


You need a JSON encoder/decoder to do that. Prototype has it implemented by default and with jQuery you can use jQuery-JSON

For example if you use Prototype as your JS library then you can convert your array into a string like that:

var example_multi_dim_arr = {"a":[1,2,3], "b": [4,5,6]};
var string_to_be_sent_to_server = Object.toJSON(example_multi_dim_arr);

And in the PHP side (assuming that the JSON string is passed to the script as a POST variable)

$multi_dim_arr = json_decode($_POST["variable_with_json"], true);

The last true field in json_decode indicates that the output should be in the form of an array ($multi_dim_arr["a"]) and not as an object ($multi_dim_arr->a).

NB! the function json_decode is not natively available in PHP 4, you should find a corresponding JSON class if you are using older versions of PHP. In PHP 5 everything should work fine.

0

精彩评论

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