---
title: "charset和URL编码关系"
author: "luolonghao"
date: "2012-03-07T12:02:31Z"
tags: []
categories: ["Web前端"]
slug: "charset-url"
draft: false
lastmod: "2012-03-07T16:59:00Z"
id: 1442622
url: "https://luolonghao.iteye.com/blog/1442622"
---

## 名词解释

charset： GBK、UTF-8、EUC-KR、Shift-JIS 等  
URL编码：HTML form提交、JS里的encodeURIComponent函数

 

## 测试环境：

服务器：本地安装Apache，www根目录下放2个HTML页面（gbk.html和utf8.html），用Fiddler查看HTTP请求，或者tail -f access\_log。

 

操作系统：Windows XP

 

浏览器版本：IE8、Firefox 10、Chrome 17、Opeara 11

 

## form提交和encodeURIComponent的区别

- form提交（application/x-www-form-urlencoded）：根据当前页面的charset进行URL编码。通过submit button提交，或者用form.submit()方法提交。在gbk.html页面【土豆】会变成【%CD%C1%B6%B9】，在utf8.html页面【土豆】会变成【%E5%9C%9F%E8%B1%86】。还有，form提交会把空格替换成加号（+），这个和RFC1738不一致，PHP里对应的函数是urlencode。
- encodeURIComponent函数：不管页面的charset，都按UTF-8来处理，所以在gbk.html和utf8.html页面上执行encodeURIComponent("土豆")之后都得到 【%E5%9C%9F%E8%B1%86】。encodeURIComponent完全符合RFC1738，会把空格替换成【%20】，PHP里对应的函数是rawurlencode。

## 浏览器地址栏行为

**1. 打开encode后的URL：**

 

GBK页面：

打开 http://localhost/gbk.html?kw=%CD%C1%B6%B9 ：

所有浏览器的地址栏直接显示 http://localhost/gbk.html?kw=%CD%C1%B6%B9。Opera比较特殊，默认隐藏GET参数部分，焦点移到地址栏时显示完整URL。

 

UTF-8页面：

打开 http://localhost/utf8.html?kw=%E5%9C%9F%E8%B1%86 ：

IE、Opera：直接显示URL，http://localhost/utf8.html?kw=%E5%9C%9F%E8%B1%86

Firefox、Chrome：把URL解码后显示， http://localhost/utf8.html?kw=土豆

 

**2. 打开encode前的URL：**

 

在浏览器地址栏直接输入带中文参数的URL按回车，有些浏览器会对中文进行URL编码，这个行为在不同浏览器不太一致。

 

打开 http://localhost/gbk.html?kw=土豆 ：

 

IE：无处理，发送 http://localhost/gbk.html?kw=土豆

Opera：URL编码， http://localhost/gbk.html?kw= %CD%C1%B6%B9

Firefox、Chrome：UTF8 + URL编码， http://localhost/gbk.html?kw=%E5%9C%9F%E8%B1%86

 

URL里带中文时需要看具体操作系统和浏览器，没有统一的标准。IE根据OS字符编码直接发送中文，Opera也是根据OS编码发送中文，只不过多一个URL编码处理。Firefox和Chrome一律按UTF-8字符处理，并进行URL编码。同事反映Firefox中文版是按OS编码发送中文，这个和Firefox本身的URL解码一起会导致BUG。

 

## 结论：

1. 避免在URL出现中文，如果需求上要求用中文，请参考2和3。
2. 如果不是ajax处理，并URL包含中文，一般是网站的搜索功能，这时GET请求最好以form方式提交，不要使用location.href之类的，这样可以始终保持一致的编码。
3. 后端获取GET数据后加is\_utf8判断，比如GBK项目的话，可以添加str = is\_utf8(str) ? utf8\_to\_gbk(str) : str; 处理，用户直接把URL改成中文时也可以返回正确的结果。

## 参考文档：

- [http://www.w3.org/TR/html401/interact/forms.html#form-content-type](http://www.w3.org/TR/html401/interact/forms.html#form-content-type)
- [https://developer.mozilla.org/en/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent)
- [http://msdn.microsoft.com/en-us/library/aeh9cef7(v=VS.85).aspx](http://msdn.microsoft.com/en-us/library/aeh9cef7%28v=VS.85%29.aspx)
- [http://cn.php.net/manual/zh/function.urlencode.php](http://cn.php.net/manual/zh/function.urlencode.php)