js把中文字串轉為gbk編碼(頁面編碼需為gbk)

來源:互聯網
上載者:User

一直以來遇到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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.