$ (). load () instead of loading the whole page, but you need to save the menu on all pages

I want to reload the content area of ​​my site using the jQuery / AJAX $().load() function. But my problem is that the header and footer should appear on all pages regardless of your url.

My site was built using templates, so for the first time I thought that I need to remove the layout output above and below the unique content, since I wouldn’t allow ie. the menu is displayed twice. But I realized that if the user does not enter my site through the first page, say index.php, he will never see the header or footer only in an uneven text page.

My question is: how would you deal with this problem? JavaScript (+ jQuery) and HTML5 are available.

+6
source share
3 answers

page.php:

 <div id="header"></di> <div id="mainContent"></div> <div id="footer"></div> 

JS:

 $("#content").load("page.php #mainContent"); //that will only load mainContent 

or

 $.get('page.php', function (data) { data = $(data).find('#mainContent').html(); $("#content").empty().append(data); }); 

See the jQuery documentation section on load () and page snippets for more information.

+5
source

It seems you may have several different options. If a user visits your site but doesn’t go to the first page, you can simply check that the header and footer appear after the page loads. If they are not found, you must create the original site layout. You can even decide to create the first page (index.php) so that each page is processed the same way.

 $(document).ready(function() { // If an element of id "header" isn't found in the DOM if (!$("#header").length() > 0) { // Generate the header and insert it as the first element of the DOM } if (!$("#footer").length() > 0) { // Generate the footer and append it to the last element of the DOM } }); 

There is no doubt about other solutions that you could entertain; you could probably include include on every page, which will only be included if the page is being requested using GET and not an AJAX request.

+1
source

The method you are looking for is known as Hijax, where you intercept the response from an AJAX request and pull out only the part of the DOM that you intend to replace on the displayed page.

The general idea is that the actual URL itself will still return the full content of the page, so if the request comes from a new visitor, the entire DOM will load, but if the request comes from the user, click the hijaxed link on your page with the specified selector CSS, then only the part of the page identified by the selector is replaced.

Take a look at Hijax, the jQuery plugin . The actual site itself is built using the plug-in, and if you look at the tab of your network and look at the inspector in your Chrome or Firebug tools, you can see that the content is exchanged without replacing the menu, title or other elements that are not replaced.

0
source

Source: https://habr.com/ru/post/913276/


All Articles