Ajax在不同瀏覽器中的相容問題比較麻煩,我在最近的項目中遇到了這個問題。並且使用了一種奇怪的方法解決了它,現在拿出來大家討論討論:
下面是前端代碼:
<script type="text/javascript">
var xmlHttp;
var as;
var state = 0;
function mouseover()
{
var id = "<%=cvE_Mail.ClientID%>";
getajax();
if (as == 0)
{
alert("Your WebBrowser do not support our service,Choose IE7 or FireFox and try again!");
}
else
{
//在回傳的時候邦定事件也不同
if (as == 1)
{
xmlHttp.onreadystatechange = myResponseHandler;
}
else
{
xmlHttp.onload = myResponseHandler;
xmlHttp.onerror = myResponseHandler;
}
//在這裡open的時候如果方式選為get,很奇怪firefox的處理端收不到傳過去的參數
//在這裡可以看到最後一個參數也是不同的,如果不這樣設定那麼返回的responseText 很有可能是空的
if (as == 1)
{
xmlHttp.open("POST", "ajax.ashx", true);
}
else
{
xmlHttp.open("POST", "ajax.ashx", false);
}
xmlHttp.send(document.getElementById(id).value);
}
};
function getajax()
{
//首先是建立的時候不同
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
as = 1;
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
as = 1;
} catch (e) {
try {
xmlHttp = new XMLHttpRequest();
as = 2;
} catch (e) {
xmlHttp = null;
as = 0;
}
}
}
}
function myResponseHandler()
{
var id = "<%=Hidebutton.ClientID%>";
if (xmlHttp.readyState == 4)
{
document.getElementById(id).value=xmlHttp.responseText;
}
};
</script>
後端代碼(asp.net):
public class CAjax : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//首先讀前端傳過來的值
HttpRequest request = context.Request;
System.IO.Stream s = request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
string request= builder.ToString();//request 就是傳過來的參數
..................
//result 為想要返回前端的結果
context.Response.Write(result);
}
}
這個方案我在firefox,ie,遨遊裡面都測試過了沒有問題,如果有感興趣的可以給我發信 :zhaotiantang520@live.cn