Ajax loads only once

I have this code:

window.onload= function() {
    window.scrollTo(0, 0.9);
    if (navigator.standalone) return;
    for (var i= document.links.length; i-->0;) {
        document.links[i].onclick= function() {
            var req= new XMLHttpRequest();
            req.onreadystatechange= function() {
                if (this.readyState!==4) return;
                document.body.innerHTML= this.responseText;
            };
            req.open('GET', this.href, true);
            req.send();
            return false;
        };
    }
};

Basically it gets href a, which is clicked and loads that href into the current body. Now the problem is that it only works once. As soon as the content is changed, as soon as I click on another link (on a new page), it is redirected and the URL changes. Then ajax works again since I really changed the pages and reset the whole thing.

I'm lost here. How can I reset my function to work forever? Thank,

Christopher

EDIT: So, I tried something like this:

function ajax(){
    if (navigator.standalone) return;
    for (var i= document.links.length; i-->0;) {
        document.links[i].onclick= function() {
            var req= new XMLHttpRequest();
            req.onreadystatechange= function() {
                if (this.readyState!==4) return;
                document.body.innerHTML= this.responseText;
            };
            req.open('GET', this.href, true);
            req.send();
            ajax();
            return false;
        };}
    }



window.onload= function() {
    window.scrollTo(0, 0.9);
    ajax();

};

But to no avail ... calling the ajax () function when it ends is clearly not enough. Can someone help me a little more: p. This is not my area of ​​expertise :).

+3
source share
5 answers

"click" <body> . DOM , , .

+2

? "? Random =" + Math.random href.

+1

, , AJAX.

window.onload , ajax.

onload , .

+1

document.body.innerHTML, , , onclick, , . .

+1

.

This is also code that suggests using the jQuery library. In this case, almost all of your code comes down to this, and also takes care of problems with multiple browsers:

$('a').live('click', function() {
    $.get( this.ref , function(data) {
        $('body').html(data);
    });
    return false;
});
-2
source

All Articles