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

一直以来遇到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" οnclick="encodeToGBK(this.previousSibling.value, function(s){alert(s)})">点击查看gbk编码</button>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值