旧行李 2018-05-07 14:32 采纳率: 25%
浏览 11

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.

  • 写回答

1条回答 默认 最新

  • ℡Wang Yan 2018-05-07 15:53
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题