26
1
最近写个程序 用jquery读取PHP的json信息,一直没注意中文的问题,今天输出中文居然出现类似”\u6210\u529f”的字符,网上查了一下,因为我页面全部用utf8编码,不存在meta的问题.
最后找到一个js版的json_decode,果然有效,贴一下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | function json_decode (str_json) { var json = this.window.JSON; if (typeof json === 'object' && typeof json.parse === 'function') { try { return json.parse(str_json); } catch(err) { if (!(err instanceof SyntaxError)) { throw new Error('Unexpected error type in json_decode()'); } this.php_js = this.php_js || {}; this.php_js.last_error_json = 4; // usable by json_last_error() return null; } } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var j; var text = str_json; cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if ((/^[\],:{}\s]*$/). test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return j; } this.php_js = this.php_js || {}; this.php_js.last_error_json = 4; // usable by json_last_error() return null; } |
原出处:http://phpjs.org/functions/json_decode:456
当前没有评论!
第一个在本文留言。