Skip to content

Instantly share code, notes, and snippets.

@fuhoi
Created June 28, 2011 04:16
Show Gist options
  • Save fuhoi/1050479 to your computer and use it in GitHub Desktop.
Save fuhoi/1050479 to your computer and use it in GitHub Desktop.
javascript-xmlhttp-request
<html>
<head>
<title>JavaScript - Xml Http Request</title>
</head>
<body>
<input type="button" value="Xml Http Request" onclick="requestFile();" />
<script language="javascript">
// Source: http://www.webdeveloper.com/forum/showthread.php?t=147342
function requestFile(){
var _xmlhttp=getXmlHttpObject();
if(_xmlhttp){alert(requestUrl(_xmlhttp, "xmlHttpRequest.xml"));}
}
function getXmlHttpObject() {
var _xmlhttp=false;
/* running locally on IE5.5, IE6, IE7 */
if(location.protocol=="file:"){
if(!_xmlhttp)try{_xmlhttp=new ActiveXObject("MSXML2.XMLHTTP");}catch(e){_xmlhttp=false;}
if(!_xmlhttp)try{_xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){_xmlhttp=false;}
}
/* IE7, Firefox, Safari, Opera... */
if(!_xmlhttp)try{_xmlhttp=new XMLHttpRequest();}catch(e){_xmlhttp=false;}
/* IE6 */
if(!_xmlhttp&&typeof ActiveXObject!="undefined"){
if(!_xmlhttp)try{_xmlhttp=new ActiveXObject("MSXML2.XMLHTTP");}catch(e){_xmlhttp=false;}
if(!_xmlhttp)try{_xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){_xmlhttp=false;}
}
/* IceBrowser */
if(!_xmlhttp)try{_xmlhttp=createRequest();}catch(e){_xmlhttp=false;}
return _xmlhttp;
} // getXmlHttpObject
function requestUrl(xmlhttp, url) {
var _reponse;
if(!xmlhttp){
_reponse="Your browser doesn't support XMLHttpRequests.";
} else {
xmlhttp.open("GET",url,true);
// make sure open appears before onreadystatechange lest IE will encounter issues beyond the first request
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState!=4)return;
if(!xmlhttp.status||xmlhttp.status==200){
_reponse=xmlhttp.responseText; // responseText or responseXML
} else {
_reponse="Request failed.";
}
};//onreadystatechange
xmlhttp.send(null);
}
return _reponse;
} //requestUrl
</script>
</body>
</html>
<?xml version="1.0"?>
<types>
<type>
<name>Direct Attack</name>
</type>
<type>
<name>Summon</name>
</type>
</types>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment