jQuery 中的 $.param() 對json數據的序列化很好用,專門針對後端作出了處理,可是畢竟不想由於這個就引入 100K 的 jquery.js 文件,因此本身參照改一個來用吧。javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>param</title> <script type="text/javascript"> var obj = { "userId": 123, "attr": [ { "id": 12, "title": "ready" }, { "id": 222, "title": "can" } ], "email": "abc@qq.com" } function param(a) { var s = [], add = function( key, value ) { s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; if (Array.isArray(a)) { for ( var v in a ) { add(v, a[v]); } } else { for ( var prefix in a ) { build( prefix, a[ prefix ], add ); } } return s.join( "&" ); } function build(prefix, obj, add) { if (Array.isArray(obj)) { for (var i = 0; i < obj.length; i++) { build(prefix + "[" + ( typeof obj[i] === "object" ? i : "" ) + "]", obj[i], add); } } else if (typeof(obj) == "object") { for ( var name in obj ) { build( prefix + "[" + name + "]", obj[ name ], add ); } } else { add( prefix, obj ); } } console.log(decodeURIComponent(param(obj))); </script> </body> </html>