一直以來遇到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&7if(!-[,1]){// also can replace by window.ActiveXObject&&document.documentModewin.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>