Last Updated: February 25, 2016
·
2.777K
· joseluisq

How to load only the body content from some static html page via Ajax.


// main.js

(function($){

    /**
        For example:
        You might load pages for each links on your menu.
        Eg.
            <ul>
                <li><a href="#about">About</a></li>
                <li><a href="#services">Services</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
    **/

    var url;
    $('#mymenu a').click(function(e){
        // Prevent the open link
        e.preventDefault();

        // Retrieve the link value and replace hash mark
        url = $(this).attr('href').replace('#', '');

        // Sets the correct page
        load_page( url + '.html' );
    });



    // The body content logic.
    function body_content_logic() {
       // Here your stuff for body content loaded data.

    }


    // Load some body content on any page.
    function load_page(url) {
      $.ajax({
            url: url,
            dataType: 'text',
            type: 'get',
            success: function(str,b,xhr){

                // Retrieve the title text (if you want)
                var title = str.match(/<(title)>[\s\S]*?<\/\1>/gi)[0].replace('<title>', '').replace('</title>', '');

                // Retrieve the body content
                str = str.match(/<(body)>[\s\S]*?<\/\1>/gi);
                str = str[0].replace('<body>','').replace('</body>', '');


                // Pay attention here:
                // All code here in this example is saved in my case at "main.js" path.
                // So, you need remove this script (or scripts) from your page "before" you embed the body content
                // for avoid duplicity code on the fly.
                str = str.replace('<script src="main.js"></script>', '');


                // Ok, now replace html body content on the current page.
                $('body').empty().html(str);


                // Change history page url (if you want)
                window.history.pushState({}, title, url);

                // Change the page's title (if you want)
                document.title = title;


                // Finally, call the method again for repeat the cycle
                body_content_logic();

            }
      });
    }


    // Apply your logic for current body content
    body_content_logic();


}(jQuery))

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside