How to load external html into a div?

50,983

Solution 1

You need to wrap your code within jQuery.ready() function since you have to wait for DOM to be fully loaded.

<script type="text/javascript">
    $(document).ready(function(){
        $('#zaladuj').click(function () { 
            $(this).load('s1.htm'); 
        }); 
    });
</script>

Solution 2

<script type="text/javascript"> 
    $('#zaladuj').click(function () { 
        $.ajax({
            context: this,
            dataType : "html",
            url : "s1.htm",
            success : function(results) {
                $(this).html(results);
            }
        });
    }); 
</script> 
Share:
50,983
user2660811
Author by

user2660811

Updated on July 09, 2022

Comments

  • user2660811
    user2660811 almost 2 years

    I've created this little code using jquery to load an external HTML file into my div, but it doesn't work, I'm running out of ideas. Any other jquery code works well. Any help appreciated:

    <div id="zaladuj"> 
    load external html file
    </div> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript"> 
        $('#zaladuj').click(function () { 
            $(this).load('s1.htm'); 
        }); 
    </script> 
    
  • user2660811
    user2660811 over 10 years
    Thanks, but it still doesn't work. Here's what JS Console gives me: Origin null is not allowed by Access-Control-Allow-Origin.
  • Fouad Fodail
    Fouad Fodail over 10 years
    @user2660811 Probably you are executing your script by double-clicking it. try to call it via a web server using localhost or something similar.