views:

45

answers:

2
+3  Q: 

JQuery Ajax Help

Hi. I have a page on my site that currently loads html via ajax. The JQuery is:

$(document).ready(function() {
$('.projects a').click(function(event) {
    $('#work').load(this.href);
    event.preventDefault();
});

});

and the html is:

<div class="projects">
    <a href="work/link.html" title="blah" id="blah">blah</a>

    <a href="work/link1.html" title="blah" id="blah">blah</a>

    <a href="work/link2.html" title="blah" id="blah">blah</a>
</div>

this works fine but my requirements have changed I would like to pull a certain area of the page i'm loading into the #work div. So I would like to say when .project a is clicked load the contents of #this div from this.href into #work. Can anyone point me in the right direction?

A: 
$(document).ready(function() {
    $('.projects a').click(function (event) {
        jQuery.get(this.href, function (response) {
            $('#work').empty().append($(response).find('#myDiv'));
        });
    });

    event.preventDefault();
});
Matt
+6  A: 

Take a look at the Loading Page Fragments section. You can target sections of the page to be loaded by adding a selector to the url string.

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

$('#result').load('ajax/test.html #container');

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

$('#work').load(this.href + ' #this');
digitaldreamer
Wow, you learn something everyday. Don't you love jQuery :)
Matt
This is really nice.
j.
@digitaldreamer thanks for the help man
mtwallet