`
zhubin215130
  • 浏览: 140148 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【转】XMLHttpRequest

阅读更多


The very first thing that we need to be able to do in order to retrieve something from the server to update the current web page (without reloading the whole page) is to create the object that will perform the processing for us. Modern browsers have a predefined class called XMLHttpRequest that we can use to define our object directly. Internet Explorer has provided five different interfaces to provide us with the functionality that we need each of which is accessed via AxtiveX. As each new version has improved the functioning of the object we want to grab the most recent version that is installed in the browser.

function createXMLHttp() {
if (typeof XMLHttpRequest != 'undefined')
return new XMLHttpRequest();
else if (window.ActiveXObject) {
var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0";, "MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for (var i = avers.length -1; i >= 0; i--) {
try {
httpObj = new ActiveXObject(avers[i]);
return httpObj;
} catch(e) {}
}
}
throw new Error('XMLHttp (AJAX) not supported');
}

var ajaxObj = createXMLHttp();





This code starts by checking if the XMLHttpRequest class exists. If it does then we use that to create our object. If it doesn't then we check if ActiveX is supported (which means that the browser is running Internet Explorer on Windows with ActiveX enabled). If it is then we try to create our object using the latest XMLHttp version (version 5.0). If that fails then we work our way back through the array trying each earlier version in turn until we find one that is installed in the browser and which therefore allows us to create our object. If all of those attempts fail or if neither XMLHttpRequest or ActiveX are supported then we throw an error to indicate that AJAX is not supported in this browser.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics