http://www.dewen.net.cn/q/9980/JQuery AJAX GBK 编

http://www.dewen.net.cn/q/9980/JQuery AJAX GBK 编码

wpjsolo
1 票
wpjsolo 53
$.ajax({
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=gb2312",
url : "",
success : function(data){}
});

虽然在contentType中指定了charset=gb2312 ,但是在Firefox用FireBug抓包发现,
Content-Type仍旧是charset=utf-8.
请问作何解?

Vinny Vinny3576 编辑于2012-12-26
评论 (0) • 举报 (0) • 分享 • 链接 • 2012-12-26 
添加评论...
2个答案 票 数
brayden认证专家
2 票
brayden6562
最佳答案
这个是浏览器行为.

我在jquery-1.10.2.js的8706行加断点, firebug调试:

点击查看原始尺寸

可以看到在传输开始时, xhr中确实设了contenttype=GBK; 但是firebug里看到,真正传输的还是utf8.

仔细看了一下jquery的代码, firefox中还是用了window.XMLHttpRequest, 可以把如下代码剥离出来放在firebug console里执行:

var xmlhttp=new window.XMLHttpRequest();
xmlhttp.open("POST","/aaa.php",false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=GBK");
xmlhttp.send('');
//xmlhttp.send();

有趣的是,xmlhttp.send()里发送空字符串'', Content-Type被firefox转为UTF-8; 假如直接发送xmlhttp.send(), 则不转换, 为GBK.

更新
JQuery 文档说:
If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

posted @ 2016-03-10 16:38  brayden  阅读(834)  评论(0编辑  收藏  举报