最近在用AJax開發服務器程序,發現IE浏覽器不支持xmlhttprequest對象,而且找不到Microsoft.XMLHTTP控件。
問題出現了我們需要解決,解決方案如下:
1、運行下regsvr32 msXML3.dll;
2、用現成的框架來做AJax;
3、代碼優化:
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
if(handle_s == null)
handle_s = "bin/normal.py/db";
this.XMLHttp.onreadystatechange = handle_l;
this.XMLHttp.open("GET",handle_s,true);
this.XMLHttp.send(null);
或判斷浏覽器
var agt = navigator.userAgent.toLowerCase();
var is_ie = (agt.indexOf("msIE") != -1);
var is_ie5 = (agt.indexOf("msIE 5") != -1);
var is_opera = (agt.indexOf("Opera") != -1);
var is_mac = (agt.indexOf("Mac") != -1);
var is_gecko = (agt.indexOf("gecko") != -1);
var is_safari = (agt.indexOf("safari") != -1);
function CreateXMLHttpReq(handler) {
var XMLhttp = null;
if (is_IE) {
// Guaranteed to be ie5 or IE6
var control = (is_IE5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";
try {
XMLhttp = new ActiveXObject(control);
XMLhttp.onreadystatechange = handler;
} catch (ex) {
// TODO: better help message
alert("You need to enable active scripting and activeX controls");
}
} else {
// Mozilla
xmlhttp = new XMLHttpRequest();
XMLhttp.onload = handler;
XMLhttp.onerror = handler;
}
return XMLhttp;
}
或者
<script language="Javascript">
var http_request = false;
function send_request(url) {//初始化、指定處理函數、發送請求的函數
http_request = false;
//開始初始化XMLHttpRequest對象
if(window.XMLHttpRequest) { //Mozilla 浏覽器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//設置MiME類別
http_request.overrideMimeType('text/XML');
}
}
else if (window.ActiveXObject) { // IE浏覽器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 異常,創建對象實例失敗
window.alert("不能創建XMLHttpRequest對象實例.");
return false;
}
http_request.onreadystatechange = processRequest;
// 確定發送請求的方式和URL以及是否同步執行下段代碼
http_request.open("GET", url, true);
http_request.send(null);
}
// 處理返回信息的函數
function processRequest() {
if (http_request.readyState == 4) { // 判斷對象狀態
if (http_request.status == 200) { // 信息已經成功返回,開始處理信息
var returnObj = http_request.responseXML;
var xmlobj = http_request.responseXML;
var employees = XMLobj.getElementsByTagName("employee");
var feedbackStr = "";
for(var i=0;i<employees.length;i++) { // 循環讀取employees.XML的內容
var employee = employees[i];
feedbackStr += "員工:" + employee.getAttribute("name");//取得標簽指定屬性
feedbackStr += " 職位:" + employee.getElementsByTagName("job")[0].firstChild.data;//取得指定標簽的最初數據
feedbackStr += " 工資:" + employee.getElementsByTagName("salary")[0].firstChild.data;
feedbackStr += "\r\n";
}
alert(feedbackStr);
} else { //頁面不正常
alert("您所請求的頁面有異常。");
}
}
}
</script>