CakePHP中的Ajax菜单

I'm learning CakePHP and I need to make an AJAX menu (a menu which doesn't reload the page once you click on the links).

I could easily do that with JavaScript with something like:

function loadPage(page) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("container").innerHTML = xhttp.responseText;
        }
    };

    xhttp.open("GET", page, true);
    xhttp.send();
}

and then call it for each button on the menu and its corresponding page, with only the HTML code that would go in the "container" id'd div:

window.onload = function() {
    document.getElementById("homeButton").onclick = function() { loadPage("home.html"); }
    document.getElementById("newsButton").onclick = function() { loadPage("news.html"); }
    document.getElementById("aboutButton").onclick = function() { loadPage("about.html"); }
    document.getElementById("registerButton").onclick = function() { loadPage("contact.html"); }
}

Well now, since I'm not very familiarized with the CakePHP framework and how it works the HTTP requests i'm having some trouble.

How would you do that in CakePHP?

I appreciate the help, good day.

Short answer: ajax layout is your friend!

Yes, you can do that with CakePHP. (You did not mention which CakePHP you are using so I will assume 2.x)

CakePHP uses the concept of layouts to render the HTML around a page, like the doctype declaration, the navigation menu and other things common to all HTML pages in your app.

When doing AJAX calls you want to get only the content of the page without this surrounding layout. To accomplish that you need to use an empty layout or the default ajax.ctp layout that CakePHP provides for you.

This is the relevant documentation from CakePHP 2.x about layouts and it talks a bit about ajax layout as well.

In short, in your controller you need to set the layout to ajax for the pages that you want to have rendered via ajax.