现在的位置: 首页 > 综合 > 正文

js把中文字符串转为gbk编码(页面编码需为gbk)

2013年09月15日 ⁄ 综合 ⁄ 共 1489字 ⁄ 字号 评论关闭

一直以来遇到gbk编码,都是要求两次encodeURIComponent去实现的。

这次的实现是才用模拟表单提交的方式去获取。具体如下代码:

/*
 * add by yansong
 * for 在gbk页面里实现字符转换成gbk编码提交到后端
 * add 传统的做法是进行两次encodeURIComponent后提交,而这个则是直接变成gbk编码,其他是页面编码必须是gbk
 */
(function(win, undefined){
	var iframeId = 'iframe_gbk', formId = 'form_gbk', inputName = 'gbk',
		doc = document,
		bd = doc.body,
		createElement = doc.createElement,
		$ = doc.getElementById;
	win.encodeToGBK = function(str, callback){
		createIframe(callback);
		createForm(str).submit();
	}
	function createIframe(callback){
		var iframe = $(iframeId);
		if(iframe)bd.removeChild(iframe);
		iframe = createElement('iframe');
		iframe.id = iframeId;
		iframe.name = iframeId;
		//iframe.src = 'about:blank';
		iframe.style.display = 'none';
		bd.appendChild(iframe);
		if(iframe.attachEvent){
			iframe.attachEvent('onload', load);
		}else{
			iframe.onload = load;
		}
		// hack for IE 6&7
		if(!-[,1]){// also can replace by window.ActiveXObject&&document.documentMode
			win.frames[iframeId].name = iframeId;
		}
		function load(){
			callback(iframe.contentWindow.location.search.split('=')[1]);
		}
	}
	
	function createForm(val){
		var form = $(formId), input;
		if(form){
			form[inputName].value = val;
			return form;
		}
		form = createElement('form');
		form.method = 'get';
		//form.action = '404.html'; 或者加上这个,但是其值必须要存在才可。
		form.target = iframeId;
		form.style.display = 'none';
		input = createElement('input');
		input.type = 'text';
		input.name = inputName;
		input.value = val;
		form.appendChild(input);
		bd.appendChild(form);
		return form;
	}
	
})(window);

测试代码:

<input type="text" name="aa" value="中国" /><button type="button" id="gg" onclick="encodeToGBK(this.previousSibling.value, function(s){alert(s)})">点击查看gbk编码</button>

抱歉!评论已关闭.