Tuesday, November 23, 2010

How to load external pages into a DIV

Loading external html pages into a DIV without having to reload the browser or using iFrames is possible using AJAX and JQuery.

First add a DIV to your html page


<div id="contentarea"></div>


Then save jquery.js file in the dame directory as your html page and add reference to jquery to the head section of your page:


<script type="text/javascript" src="jquery.js"></script>


Then add the following script to the head section:


<script type="text/javascript">
<!--

$(document).ready(function(){
ajaxpage("http://elena-sqldba.blogspot.com", 'contentarea');
});


function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false

page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}

page_request.open('GET', url, true)
page_request.send(null)

}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
var divElement = document.getElementById(containerid);
divElement.innerHTML = '';

try {
divElement.innerHTML = page_request.responseText;
}
catch (e) {
// IE fails unless we wrap the string in another element.
var wrappingElement = document.createElement('div');
wrappingElement.innerHTML = page_request.responseText;
divElement.appendChild(wrappingElement);
}
} //end if
}



// -->
</script>

No comments:

Post a Comment