简体   繁体   中英

Keep PHP includes/requires when loading new page through AJAX

I have a site which has a main page containing header/navbar/footer and then the content is AJAXd into a div: <div id="content" class="page-content"></div>

Is it possible to dynamically load a page into the content div using AJAX, keeping the current page variables in PHP?

This is so I don't have to write the requires and includes on every single page, and should improve load performance as well.

In a typical web request/response paradigm, each request to a page is independent from the others. This mean that if you make a request for a first page and then a second one, the two processed request will not share any information or status. This is why we call this kind of client/server communication "stateless". Of course we can buidl a "stateful" system on top of this kind of communication, with session data or a database, but this is beyond the point.

In a similar way, in the structure you propose, you'll have a first request to load the container page, and a second one or more to load the content to inject in the first one. Those will be separated calls, isolated from each other, unable to share any variable or required script.

But that's not a problem. Nor it is a big overhead. There is another reason you don't want to repeat code: keeping thing DRY (Don't Repeat Yourself). This is because you don't want to mantain similar but duplicated code, where each update would need to be repeated in different parts of your program.

In your tipical situation, you will end up with a script which will make all the common work needed in your pages. Both the container page and the content pages will require this common script.

So, you write the needed code only once, but it will be executed for every request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM