note 72489 deleted from function.json-decode by googleguy
| From: | googleguy@php.net | Date: | Fri, 30 Nov 2012 05:51:58 +0000 |
| Subject: | note 72489 deleted from function.json-decode by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192226@lists.php.net to get a copy of this message | ||
Note Submitter: paul at sfdio dot com
----
I've written a javascript function to get around this functions limitations and the limitations
imposed by IE's lack of native support for json serialization. Rather than converting variables
to a json formatted string to transfer them to the server this function converts any javascript
variable to a string serialized for use as POST or GET data.
String js2php(Mixed);
js2php({foo:true, bar:false, baz: {a:1, b:2, c:[1, 2, 3]}}));
will return:
foo=true&bar=false&baz[a]=1&baz[b]=2&baz[c][0]=1&...etc
function js2php(obj,path,new_path) {
if (typeof(path) == 'undefined') var path=[];
if (typeof(new_path) != 'undefined') path.push(new_path);
var post_str = [];
if (typeof(obj) == 'array' || typeof(obj) == 'object') {
for (var n in obj) {
post_str.push(js2php(obj[n],path,n));
}
}
else if (typeof(obj) != 'function') {
var base = path.shift();
post_str.push(base + (path.length > 0 ? '[' + path.join('][') +
']' : '') + '=' + encodeURI(obj));
path.unshift(base);
}
path.pop();
return post_str.join('&');
}