简体   繁体   中英

Jquery ajax append html file based on url

so far i have a simple script to include few html files on all pages. What i would like to achieve is to include specific file based on the folder in the url that visitor is currently on and define those folder names, for example:

  • If /page-1/index-1.html (include demo-1.html)
  • If /page-1/index-2.html (include demo-1.html)
  • If /random-page/test.html (include demo-1.html)
  • If /page-2/index-1.html (include demo-2.html)
  • If /page-2/index-2.html (include demo-2.html)
  • If /another-folder/test.html (include demo-2.html)
  • ... and so on

Currently i include both demo-1.html and demo-2.html on all pages, but this is not working for me as the content inside those two files is different per folder. The script i use:

$.ajax({ url: "../include/demo-1.html", success: function (data) { $('body').append(data); }, dataType: 'html' });

Any help appricieted, thanks :)

With a help from a stackoverflow user who posted an answer in a similar thread found here , i've came up with a working solution (not sure if it's optimised well, but it works):

$(function() {
    var currentURL = window.location.href;
    if(/folder-name/.test(currentURL)) {
        $.ajax({
            url: "../include/demo-1.html",
            success: function (data) { $('body').append(data); },
            dataType: 'html'
        });
    };
    if(/another-folder-name/.test(currentURL)) {
        $.ajax({
            url: "../include/demo-2.html",
            success: function (data) { $('body').append(data); },
            dataType: 'html'
        });
    };
    // etc...
});

Hope this helps someone else with same question.

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