views:

459

answers:

2

Hi, I'm trying to make a proof of concept website, but I want perfect degradation. As such I'm going to code the website in plain XHTML first and then add classes & ids to hook them in jQuery.

One thing I want to do is eventually enable Ajax xmlhttprequest for all my links, so they display in a viewport div. I want this viewport to be a "universal" dump for any xmlhttprequest from multiple external pages.

I was wondering if I'm able to hardcode something like:

<a href="blah.html" class="ajax">, <a href="bleat.html" class="ajax">

etc. So as you can see, I give all link tags that I want to call Ajax requests from with the class ajax. In my JS based on jQuery, I want to be able to code it such that all positive ${"a").filter(".ajax") will automatically load their respective hrefs [variable] as a ajax request.

Please help. I'm a n00b.

A: 

With your example, you should be able to do:

$('.ajax').click(function () { 
    // Your code here. You should be able to get the href variable and
    // do your ajax request based on it. Something like:
    var url = $(this).attr('href');
    $.ajax({
        type: "GET",
        url: url
    });
    return false; // You need to return false so the link
                  // doesn't actually fire.
});

I would suggest using a class different from "ajax" because it makes the code a little strange to read, because $('.ajax') could be misread as $.ajax().

The $('.ajax').click() part registers an onClick event handler for every element on the page with the class "ajax" which is exactly what you want. Then you use $(this).attr('href') to get the href of the particular link clicked and then do whatever you need!

OverloadUT
Thank you so much!
A: 

Something like:

function callback(responseText){
    //load the returned html into a dom object and get the contents of #content
    var html = $('#content',responseText)[0].innerHTML;
    //assign it to the #content div
    $('#content').html(html);
}

$('a.ajax').click(function(){
    $.get(this.href, callback);
    return false;
});

You need to parse out everything that is outside of the #content div so that the navigation isn't displayed more than once. I was thinking about a regexp but probable easier to use jquary to do it so I updated the example.

Annan
Thank you so much!