How to load new content into an existing page element the easy way
Imagine you have a DIV on your page, and when a user clicks a link we want to replace the contents of that DIV with the HTML stored in a different file on our server. The easiest way to accomplish this is with the .load() method.
$("#mylink").click( function () {
$("#mydiv").load("page2.htm");
return false;
});
Here we have set up an event handler. But it's the second line that really does what we're after. It gets a reference to our DIV, then says to load the contents of "page2.htm" into that DIV. That's it. All nice and easy.
But there are always those situations which do not quite fit into the "nice and easy" category. Perhaps we need to take some action after the content is loaded. The .load() method allows for some of these needs, but to really cover all the Ajax needs, look into the $.ajax() method.
In cases where you need to pass data to your called page, you can use an object containing property/value pairs as the optional second parameter.
$("#mydiv").load("page2.php", { id: 4, name: "Bob" });
And in the cases where you need to do further action after loading the content into the DIV (maybe assigning event handlers to the new content?) a function can be passed as the third parameter (or second if the data parameter is omitted).
$("#mydiv").load("page2.php",
{ id: 4, name : "Bob" },
function () { $("#mydiv a").click( function () {
alert("I was clicked");
return false;
}
}
);
Here we are changing the event handler of the anchor tags that were in the loaded content. But, we are not limited to assigning event handlers - we can do whatever we'd like in the .load() methods callback function.
- Printer-friendly version
- Login or register to post comments

This doesn't work. You could
This doesn't work. You could at least supply examples.
TMW2jDRc
drug testing
home test kits
detox drinks
drugtests
lemon detox