Is there a way to make normal links automatically load via ajax and not normal?

I didn't explain it very well.

But I mean if I have an ajax script that loads the content of a page into a DIV element using the loadpage ('whatever.php') function; instead of manually traversing this path to all links, is there a way to have a script that automatically makes all regular links load via this ajax function?

Like Facebook, your profile is loaded via ajax, but if you look at their code, they just have a regular profile link.

Hooray!

+2


source to share


4 answers


You can of course do this with jQuery.

This script goes through the document, finds each anchor element, and binds an event handler to the click event of each one. When the anchor element is clicked, the event handler detects the href attribute and loads that page in #targetDiv (you can of course call this div no matter what you want).



<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
  $("a").click(function() {
    $("#targetDiv").load(($(this).attr("href") + " body");
    return false;
  });
});
</script>

...

<!-- In your document body, this is the div you'd load the pages into. -->
<div id="targetDiv"></div>

      

+6


source


You can use JQuery for this (if I understand your question correctly).

First, you can make the loadpage () function like this:



function loadpage(divId, url) {
    $('#' + divId).load(url);

    return false;
}

      

.load () is not supported by all browsers. If you want to do it without .load (), then you can check .get (). For more information on .load (), take a look at http://docs.jquery.com/Ajax/load

+1


source


I assume it will look something like this:

$(document).ready(function(){
    $("a").click(function(){
        $("body").load($(this).attr("href") + " body");
        return false;
    });
});

      

This would make all the tags <a>

on the page a call to a function that loads the HTML document from the href

tag attribute , strips out its body tag, and replaces the content of the current page's tags with the contents of the new body tag. Thus, it is easier to work with this without JavaScript and also integrate it into an existing site.

To use it, you put it in a tag <script>

at the beginning of the main page or in an external JS file.

Note, however, that this code only updates the content of the tag <body>

, the head (including the title tag) remains intact. You might need to add some extra code to update things like this.

+1


source


Simple and enjoyable. Check it out: Bjax

Using:

<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />

      

Finally, include this in the HEAD of your html:

$('a').bjax();

      

For more settings, you can watch a demo: Bjax Demo

+1


source







All Articles