http,javascript的编码解码
请求与响应的编码应分开分析
两者的编码,解码处理是相对独立的流程
依赖于相对独立的header: request header, response header
ajax相关
http的请求分三部分
header iso-8859-1
uri utf-8编码(待实验)
body utf-8编码(待实验)
响应
header iso-8859-1
body 由服务器指定编码方式
响应的数据由浏览器根据返回的头部的编码方式解码
解码后传递给 javascript处理
最好在响应头部指定具体的编码方式
eg
- </pre><p><pre name="code" class="html"><!doctype html>
- <html>
- <head>
- <meta charset="GBK">
- <script src="jquery.js"></script>
- <script src="app.js"></script>
- </head>
- <body>
- <div>
- </div>
- </body>
- </html>
app.js
访问 b.jsp butf8.jsp均正常显示中文
- $(function(){
- $.ajax({
- "url": "b.jsp", // "url": "butf8.jsp",
- "type": "get",
- "dataType": "json",
- "success": function(data){
- alert(data["yy"]);
- $("div").text(data["yy"]);
- }
- });
- });
b.jsp
保存为gbk文件
- <%@ page contentType="text/json;charset=gbk" %>
- <%
- out.println("{\"中文\":\"xx6\",\"yy\":\"英文6\"}");
- %>
butf8.jsp
保存为utf8文件
- <%@ page contentType="text/json;charset=utf-8" %>
- <%
- out.println("{\"中文\":\"xx5\",\"yy\":\"英文5\"}");
%>
======================================
app.js
- $(function(){
- $("#ss").on("click", function(){
- var p = $("p").text();
- alert(p);
- var pp = {"a": p+p, "b":"1"};
- alert(JSON.stringify(pp));
- $.ajax({
- "url": "b.jsp",
- "contentType":"text/json",
- "data": JSON.stringify(pp),
- //"data":pp,
- "type": "post",
- "dataType": "json",
- "success": function(data){
- //alert(data["yy"]);
- $("div").text(data["yy"]);
- $("p").text(data["yy"]);
- }
- });
- });
- });
b.jsp
- <%@ page import="java.io.InputStream" %>
- <%@ page contentType="text/json;charset=gbk" %>
- <%
- out.println("{\"中文\":\"xx6\",\"yy\":\"英文6\"}");
- %>
- <%
- byte[] bytes = new byte[1024 * 1024];
- InputStream is = request.getInputStream();
- int nRead = 1;
- int nTotalRead = 0;
- while (nRead > 0) {
- nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
- if (nRead > 0)
- nTotalRead = nTotalRead + nRead;
- }
- String str = new String(bytes, 0, nTotalRead, "gbk");
- System.out.println("Str:" + str);
- %>
原文为 "英文6英文6"
输出为 Str:{"a":"鑻辨枃6鑻辨枃6","b":"1"}
- String str = new String(bytes, 0, nTotalRead, "utf-8");
输出为 Str:{"a":"英文6英文6","b":"1"}
说明: javascript提交时("contentType":"text/json",),("contentType":"application/json"), 直接把 英文6英文6 编码为 utf-8 字节流
post观察的内容为: {"a":"鑻辨枃6鑻辨枃6","b":"1"}
按gbk解码为 "鑻辨枃6鑻辨枃6" , 按utf-8解码为 英文6英文6
********************
post缺省提交时a=%E8%8B%B1%E6%96%876%E8%8B%B1%E6%96%876&b=1
utf-8 uriencode