Gzip已的JavaScript实现 [英] JavaScript implementation of Gzip
问题描述
我正在写,需要通过AJAX(思来存储JSON数据在一个小的,固定大小的服务器端缓存的Web应用程序:<一href="http://$c$c.google.com/apis/opensocial/articles/persistence-0.8.html#restrictions-quotas">Opensocial配额的)。我没有对服务器的控制。
I'm writing a Web application that needs to store JSON data in a small, fixed-size server-side cache via AJAX (think: Opensocial quotas). I do not have control over the server.
我需要降低存储的数据留在服务器端配额内的大小,并希望能够将其发送到服务器之前gzip压缩的字符串化的JSON在浏览器中。
I need to reduce the size of the stored data to stay within a server-side quota, and was hoping to be able to gzip the stringified JSON in the browser before sending it up to the server.
不过,我找不到太多的Gzip已对JavaScript实现的方式。对于任何建议,我怎么能融为一体preSS在发送之前在客户端的数据?
However, I cannot find much in the way of JavaScript implementations of Gzip. Any suggestions for how I can compress the data on the client side before sending it up?
推荐答案
修改似乎有一个能够正确处理统一code字符串在<一个更好的解决方案,LZW href="http://pieroxy.net/blog/pages/lz-string/index.html">http://pieroxy.net/blog/pages/lz-string/index.html (感谢在评论pieroxy)。
Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).
我不知道任何gzip的实现,但 jsolait库(该网站似乎已经消失)有LZW COM功能pression / DECOM pression。在code是 LGPL 。
I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
这篇关于Gzip已的JavaScript实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!