javascriptjqueryajaxjquery-load

How to use jquery.load to retrieve a part of an html/ or a full html?


I'm trying to load an entire/partial html using jquery's load function. I'm aware that this can also be done using $.ajax() but I want to learn how to use the different functions of jquery.

Here's my current code:

<ul>
    <li><a id="home" href="#">Home</a></li>
    <li><a id="contact" href="#">Contact</a></li>
    <li><a id="gallery" href="#">Gallery</a></li>
</ul>


<div id="result">

</div>

<script>
$(document).ready(function(e) {
    $("#gallery").click(function(e){
        $('#result').load('gallery.html');
        e.preventDefault();
    });
 });
</script>

currently it's not working and I'm also getting this enter image description here

XMLHttpRequest cannot load file:///C:/Users/randel/Desktop/cis/gallery.html. Origin null is not allowed by Access-Control-Allow-Origin.


Solution

  • jQuery can't retrieve files from your filesystem. You have to move your project to a web server or a local development server like XAMPP or similar

    Other than that your code should work. Just remember to put e.preventDefault() before everything else:

    $("#gallery").click(function(e){
        e.preventDefault();
        $('#result').load('gallery.html');
    });