请有人告诉我为什么这段代码适用于 IE 中的所有浏览器,我似乎找不到问题所在,是兼容性问题还是我的代码缺少 Microsoft 需要的东西,这段代码旨在提交表单并获取来自 XMLHttpRequest 对象的响应
//defining XHR object
function createXHR() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else { // code for IE6, IE5
//return new ActiveXObject("Microsoft.XMLHTTP");
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
} else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (ex) {
return null;
}
}
}
}
//function to make parameter and value pairs
function encodeNameAndValue(sName, sValue) {
var sParam = encodeURIComponent(sName);
sParam += "=";
sParam += encodeURIComponent(sValue);
return sParam;
}
//function to get the form fields
function getRequestBody(oForm) {
//array to hold the params
var aParams = new Array();
//get your reference to the form
var oForm = document.form1;
//iterate over each element in the form-
for (var i = 0; i < oForm.elements.length; i++) { //start of for loop to loop through form elements---
//get reference to the field
var oField = oForm.elements[i];
//different behavior based on the type of field----------------- switch statement---------------
switch (oField.type) {
//buttons - we don’t care
case "button":
case "submit":
case "reset":
break;
//checkboxes/radio buttons - only return the value if the control is
//checked.
case "checkbox":
case "radio":
if (!oField.checked) {
break;
}
//text/hidden/password all return the value
case "text":
case "hidden":
case "password":
aParams.push(encodeNameAndValue(oField.name, oField.value));
break;
//everything else
default:
switch (oField.tagName.toLowerCase()) {
case "select":
aParams.push(encodeNameAndValue(oField.name,
oField.options[oField.selectedIndex].value));
break;
default:
aParams.push(encodeNameAndValue(oField.name,
oField.value));
}
}
} //end of for loop
return aParams.join("&");
}
//function to make the make asynch request
function sendRequest() {
var oForm = document.form1;
var sBody = getRequestBody(oForm);
var oXHR = createXHR();
oXHR.open("post", oForm.action, true);
oXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXHR.onreadystatechange = function () {
if (oXHR.readyState == 4) {
if (oXHR.status == 200) {
//---------------------------------------------------
saveResult(oXHR.responseText);
} else {
saveResult("An error occurred: " + oXHR.statusText);
//---------------------------------------------------
}
}
};
oXHR.send(sBody);
}
//function to send data to the display div
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "" + sMessage;
}