鍍金池/ 問答/HTML/ js請求gbk接口的問題

js請求gbk接口的問題

前端是vue,后端是java,現(xiàn)在后端接口是gbk的,前端如何改成能夠正常調(diào)用接口?尤其是請求參數(shù)如何轉(zhuǎn)gbk?

網(wǎng)上找到了這段

1、對傳入的GBK字符串,要用數(shù)據(jù)流接收,具體到angularjs中,$http 請求中需要覆蓋參數(shù)responseType , responseType: "arraybuffer",


$http({
  method: "POST",
  responseType: "arraybuffer",
  url: "restcater/cenchain/findCenChain",
  data: branchlist
})
2、解析
var x = new Uint8Array(resp.data);

var str =new TextDecoder('gbk').decode(x);

已經(jīng)正常識別了。
/////////////////////////////////////////////////////////
3、UTF-8提交的數(shù)據(jù)轉(zhuǎn)為GBK,要引用第三方JS庫

https://github.com/inexorabletash/text-encoding

<script>
  // var TextEncoderOrg = window.TextEncoder;
  // ... and deactivate it, to make sure only the polyfill encoder script that follows will be used
  window.TextEncoder = null;
</script>
<script src="lib/text-encoding/encoding-indexes.js"></script>
<script src="lib/text-encoding/encoding.js"></script>
  //獲取GBk編碼的int8數(shù)組 
var uint8array =  new TextEncoder("gbk",{ NONSTANDARD_allowLegacyEncoding: true }).encode(string);
 // 放入blob中準備上傳
 var blob=new Blob([uint8array],{type:"text/plain"});

但實際使用UTF-8提交的數(shù)據(jù)轉(zhuǎn)為GBK這個似乎沒有用啊,轉(zhuǎn)出來得到的uint8array 是個數(shù)組,調(diào)用接口參數(shù)還需要進行des加密,需要變成字符串,這又要怎么做呢?

回答
編輯回答
瘋子范

AJAX 請求,參數(shù)值的編碼要使用 encodeURIComponent ,它只支持 UTF-8 的字節(jié)結(jié)果,無法產(chǎn)生 GBK 的字節(jié)結(jié)果。
form 提交,可以使用 accept-charset 屬性指定編碼的字節(jié)結(jié)果。(form 的話自己好像就會根據(jù)頁面的 charset 來默認編碼了)

2017年9月12日 19:22