xmlHttpRequest中⽂乱码问题
⾸先xmlHttpRequest 使⽤Post时,需要对数据进⾏编码,在客户端⼀般使⽤js中的encodeURIComponent
在fig中指定了gb2312编码后,在aspx页⾯中如果直接使⽤ Request[xxx]那么结果将会出现乱码,
原因是asp系统使⽤gb2312编码对上传的数据进⾏解码还原,⽽encodeURIComponent编码是按uft-8来的.
为了避免这个问题,我们需要见xmlHttpRequest发送上来的原始数据(字节)按utf-8进⾏解码处理,url编码和utf8区别
⽅式⼀
代码如下
浏览器端(js):
function myXMLHttpRequest(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlHttp=myXMLHttpRequest();
content = "user="+encodeURIComponent("⼤发啊个啊按时法⽶]]吗吗吗*-234^342942023&^+//");
content +="&data=" +encodeURIComponent("到这⾥结束了!");
xmlHttp.Open("POST", "doc.aspx", false);
xmlHttp.setRequestHeader("Content-Length",content.length);
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
xmlHttp.Send(content);
服务器端(asp)
Byte[] bytes= Request.BinaryRead(Request.ContentLength);
NameValueCollection req= FillFromEncodedBytes(bytes, Encoding.UTF8);
Response.Write(req["User"]);
其中FillFromEncodedBytes定义如下(这个是ms内部代码,通过reflector 获得,作⽤就是根据url编码将字段跟数据分解出来)略有改动
private NameValueCollection FillFromEncodedBytes(byte[] bytes, Encoding encoding)
{
NameValueCollection _form = new NameValueCollection();
int num = (bytes != null) ? bytes.Length : 0;
for (int i = 0; i < num; i++)
{
string str;
string str2;
int offset = i;
int num4 = -1;
while (i < num)
{
byte num5 = bytes[i];
if (num5 == 0x3d)
{
if (num4 < 0)
{
num4 = i;
}
}
else if (num5 == 0x26)
{
break;
}
i++;
}
if (num4 >= 0)
{
str = HttpUtility.UrlDecode(bytes, offset, num4 - offset, encoding);
str2 = HttpUtility.UrlDecode(bytes, num4 + 1, (i - num4) - 1, encoding);
}
else
{
str = null;
str2 = HttpUtility.UrlDecode(bytes, offset, i - offset, encoding);
}
_form.Add(str, str2);
if ((i == (num - 1)) && (bytes[i] == 0x26))
{
_form.Add(null, string.Empty);
}
}
return _form;
}
---------------------------------------------------------
⽅式⼆,使⽤GET⽅式发来的请求,上⾯(⽅式⼀)的每个字段也可以使⽤下⾯⽅式进⾏转换
客户端:(使⽤Utf-8编码⽅式)
/services/regServices.aspx?username='+encodeURI(un.value)
服务端:(默认情况下,Request["xxx"]使⽤gb2312进⾏UrlDecode处理,所以将结果按gb2312 UrlEncode,后再使⽤utf-8进⾏UrlDecode)    string data1 = Util.GetQ("username", "");
string data2= HttpUtility.UrlEncode(data1, Encoding.GetEncoding("GB2312"));
string username = HttpUtility.UrlDecode(data2, Encoding.UTF8);
⽅式三,处理⽅式类似第⼀种,因为要获取的Get,中的Query
IServiceProvider provider = (IServiceProvider)HttpContext.Current;
HttpWorkerRequest wr= provider.GetService(typeof(HttpWorkerRequest)) as HttpWorkerRequest;        byte[] bytes = wr.GetQueryStringRawBytes();
NameValueCollection req = FillFromEncodedBytes(bytes, Encoding.UTF8);
string u = req["username"];

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。