Search code examples
jqueryjquery-load

jQuery Load Problem


Still new to jQuery, need help on following:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

<script type="text/javascript">
     $(document).ready(function() {
         $('.nav-link').click( function() {
            var href = $(this).attr('href');
            $('#content').load( href, function() {
                alert("Yeahhhh !");
            });
            return false; // don't actually follow the link
         });
     });
</script>

<div class="menu">
    <ul>
    <li><a href="http://www.google.com.my/" class="nav-link"> Yeah 1 </a></li>
    <li><a href="C:\Testing\Yeah1.html" class="nav-link"> Yeah 2 </a></li>
    </ul>
</div>


<div id="content">
    ... Initial Content...
</div>  
 </body>
 </html>

I created this HTML file called testing.html and have another simple HTML file called yeah1.html for testing purpose. Before putting the jQuery codes, the link could be directed to yeah1.html.

However, after putting the jQuery codes, the $('#content').load( href); should be able to load the content in its DIV and I've even got the message alert of "Yeahhhh !"...but, still the content is not loaded.


Solution

  • A lot of browsers (Chrome, FF) will block files being loaded directly from your disk for security reasons.

    When you refer to the file using C:\..., the protocol if file. The link ultimately looks like this:

    <a href="file:///C:\Testing\Yeah1.html" class="nav-link"> Yeah 2 </a>
    

    To fix it, put the Yeah1.html file in your website's virtual folder and use a absolute or relative path to load it via http protocol.

    (relative path)

    <a href="Yeah1.html" class="nav-link"> Yeah 2 </a>
    

    or (absolute path)

    <a href="/Yeah1.html" class="nav-link"> Yeah 2 </a>
    

    or (absolute path, fully specified)

    <a href="http://mysite.com/Yeah1.html" class="nav-link"> Yeah 2 </a>
    

    That and then as Dennis mentioned, load is failing in your case due to Same origin policy violation. So you can get Yeah1,html to load, but call to google.com will fail unless you switch to jsonp

    function jsonpCallback(data, status) {
        alert("data: " + data + ", status: " + status);
    }
    
    $.ajax({
        url: "http://www.google.com.my/",
        dataType: 'jsonp',
        jsonpCallback: 'jsonpCallback',
    });