budding_fed
budding_fed

Reputation: 71

JQuery load local files dynamically

I am developing a HTML prototype, all the static content in the page is saved in different files. I want to use these files as includes in my HTML prototype. Below is HTML code for calling the two HTML include files.

<div class="include-file" file="header.html"></div>
<div class="include-file" file="footer.html"></div>

I am using jquery load() method to include these files.

$(function () {
    var fileName = $(".include-file").attr('file');
     $(".include-file").load(fileName);
});

This function works fine when i am including only one file in a page.

Issues:

1.When I include two files the second file(footer.html) doesn't load,and first file(header.html)loads twice.

2.Single file loading works in FF,IE9 but doesn't work in Chrome.(Note: All files are local, I am not planning to use a web server, as this is just a prototype)

Upvotes: 1

Views: 7087

Answers (2)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You are using same filename on each .load. Try something like below,

$(function () {
    $(".include-file").each (function () {
       $(this).load($(this).attr('file'));
     });
});

This should fix your first problem.

Try Ways to circumvent the same-origin policy for your second problem.

Upvotes: 5

Chris
Chris

Reputation: 769

$(".include-file").load(fileName);

This line loads for all elements with selector of class "include-file", so for BOTH elements.

EDIT: maybe you could also use the following (not tested)

$('div[file="'fileName'"').load(fileName);

Upvotes: 0

Related Questions