safari的url地址转义问题
调用页面:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<a id="login" target="_blank">test</a>
</body>
<script type="text/javascript">
var name = "中文用户名";
var pass = "123";
var url = "test.ashx";
url += "?name=" + escape(name);
url += "&password=" + pass;
document.getElementById("login").href = url;
</script>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<a id="login" target="_blank">test</a>
</body>
<script type="text/javascript">
var name = "中文用户名";
var pass = "123";
var url = "test.ashx";
url += "?name=" + escape(name);
url += "&password=" + pass;
document.getElementById("login").href = url;
</script>
</html>
处理页面:
<%@ WebHandler Language="C#" Class="test" %>
using System;
using System.Web;
public class test : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (context.Request["name"] == "中文用户名" && context.Request["password"] == "123") {
context.Response.Write("ok");
} else {
context.Response.Write("error");
}
}
public bool IsReusable {
get {
return false;
}
}
}
using System;
using System.Web;
public class test : IHttpHandler {
public void ProcessRequest (HttpContext context) {
if (context.Request["name"] == "中文用户名" && context.Request["password"] == "123") {
context.Response.Write("ok");
} else {
context.Response.Write("error");
}
}
public bool IsReusable {
get {
return false;
}
}
}
用safari浏览,传输到服务器端时,转义后的url会变成:
name=%25u4E2D%25u6587%25u7528%25u6237%25u540D&password=123
而别的浏览器则是:
name=%u4E2D%u6587%u7528%u6237%u540D&password=123
可见,作为url传递时,safari把%也转义了,escape("%")正好等于 %25
可见,作为url传递时,safari把%也转义了,escape("%")正好等于 %25
这儿的解决方式是:
使用:encodeURI() 来转义,即按 UTF-8 来编码。
关于:
escape() encodeURI() encodeURIComponent() 的差别,可以看这篇文章:
javaScript中URL编码转换,escape() encodeURI() encodeURIComponent
escape() 方法:
采用ISO Latin字符集对指定的字符串进行编码。所有的空格符、标点符号、特殊字符以及其他非ASCII字符都将被转化成%xx格式的字符编码(xx等于该字符在字符集表里面的编码的16进制数字)。比如,空格符对应的编码是%20。unescape方法与此相反。不会被此方法编码的字符: @ * / +
encodeURI() 方法:
encodeURI() 方法:
把URI字符串采用UTF-8编码格式转化成escape格式的字符串。不会被此方法编码的字符:! @ # $& * ( ) = : / ; ? + '
encodeURIComponent() 方法:
把URI字符串采用UTF-8编码格式转化成escape格式的字符串。与encodeURI()相比,这个方法将对更多的字符进行编码,比如 / 等字符。所以如果字符串里面包含了URI的几个部分的话,不能用这个方法来进行编码,否则 / 字符被编码之后URL将显示错误。不会被此方法编码的字符:! * ( )