我们在调用数据的时候经常需要通过ajax请求将参数传到后台接口,在传递参数的过程中,往往会遇到中文编码转换的问题。例如:
某“charset=gb2312”页面
此时点击查询按钮,获取var keyword=$("#kword").val(),你会发现keyword= %E6%89%8B%E6%9C%BA ,这是被编码后的中文,传入后台无法识别。
这时候,就必须对中文进行转码,首先将中文转化为Unicode编码,后台再进行解码:
前台js函数:
// 汉字转换成Unicode
function StringToUnicode(str) {
if (!str) {
return;
}
var unicode = '';
for (var i = 0; i < str.length; i++) {
var temp = str.charAt(i);
if (isChinese(temp)) {
unicode += '\\u' + temp.charCodeAt(0).toString(16);
}
else {
unicode += temp;
}
}
return unicode;
}
// 判断字符是否为汉字,
function isChinese(s) {
return /[\u4e00-\u9fa5]/.test(s);
}
获取到的keyword经过编码就会变成类似于 \u624b\u673a 这样的Unicode编码。
后台接收该参数,转化为中文:
/// <summary>
/// Unicode转化为中文
/// </summary>
/// <param name="unicode"></param>
/// <returns></returns>
public string UnicodeToString(string unicode)
{
string result = "";
Regex reg = new Regex(@"\\u([0-9a-f]{4})");
result = reg.Replace(unicode, delegate (Match m)
{
return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
});
return result;
}