Last Updated: February 25, 2016
· joseluisq

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

// main.js


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

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

        // 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) {
            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.

                // 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


    // Apply your logic for current body content