Load content from another file using jQuery/Ajax

by Dave Reeder 1. September 2009 22:14

Imagine you want to grab text from a document and add it into a div on your page.
This is easily done with jQuery.

We start off with our HTML file:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - load content into a div</title>
</head>
<body>

<div id="content"></div>

</body>
</html>

Notice we have put a div called "content" into the body. We will load content into this div.

Next we need to load our main jQuery file:


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

And finally we add our function to load the content over from the other file. Note, our other file is called "hello-world.html" and we use the document.ready() function to load the content when the page loads:


<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function() {
			$("#content").load("hello-world.html");
	})
</script>

Our overall page is:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - load content into a div</title>

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function() {
			$("#content").load("hello-world.html");
	})
</script>
</head>
<body>

<div id="content"></div>

</body>
</html>

View a Demo Here

Tags: , , ,

Comments

9/21/2009 3:25:29 AM #

thank you for sharing.. very nice blog u have here

Free Blackberry Applications

10/16/2009 6:43:09 AM #

Thank You Thank You Thank You!  I'm just getting into jquery...if you can't tell by my enthusiasm.  I was looking for this code because I didn't want to have to use php and rename all of my files or rewrite my htaccess file.  I knew there would be a simple solution to do this.  

Mary

1/28/2010 9:52:12 PM #

For every disciplined effort there is a multiple reward.

Loans in Oregon

Comments are closed