简体   繁体   中英

Javascript dynamically load html into another html file

I have one main html file which looks like this:

    <head>
css here
    </head>

    <body>

    <div class="nav">
    ....
    </div>

<div id="mainpage-load">

    <div id="loading">
        <img src="./img/loading-white.gif">
    </div>

</div>

<script> jquery </script>
<script> slider.js </script>
<script> ... </script>
<script> APP.JS </script>

i want to dynamically load content into the div "mainpage-load". but when i load the content with jquery/ajax .load into the div, the javascript file for a slider for example is not effecting the new content.

app.js to load content:

$(function(){
    var $loading = $('#loading').hide();
    $(document)
      .ajaxStart(function () {
        $loading.show();
      })
      .ajaxStop(function () {
        $loading.hide();
      });

    $('#load-it').on('click', function(e){
      e.preventDefault();
      $( "#mainpage-load" ).load( "pages/main.html" );
    })
});

2nd html file (pages/main.html):

<div class="new content">
new content here
</div>

i tried putting app.js and jquery into the but still not working or putting the slider.js in the pages/main.html

thanks in advance !

You just try this.

jQuery:

$("#y").load("home.html");

javascript:

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

I wrote a simple example and hope it will help you: you can find a demo here and the solution files here

html part :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div class="nav">

  </div>

  <div id="mainpage-load">
    
    <div id="loading" >
       <img src="./img/loading-white.gif">
    </div>

  </div>
  <button id="loadcontent">Load Content</button>


  <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="app.js"></script>
</body>
</html>

JavaScript app.js :

(function($){
  $(document).ready(function(){
   
     $(document).on("click", "#loadcontent", function(){
        $(document).load( "pages/main.html", function(resp, status, xhr){
            $("#loading").show();
            if (status == "success" && xhr.status == 200)
              $("#mainpage-load").prepend(resp);
            else{
                console.log("something wrong happend!");
            }
            $("#loading").hide();
        });
       
     });
    
  });
})(window.jQuery);

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