Search code examples
jqueryhtmlextend

Extending Jquery : To Render Partial


I'm trying to write a function that extends jquery. It appears to be working but I get this error when trying to use it.

XMLHttpRequest cannot load file:.../WebstormProjects/JQuery.FormHelpers/_partial.html. Origin null is not allowed by Access-Control-Allow-Origin.

js

$.fn.partial = ($,function partial(source){
    $.get(source,function(data){
        if(!data){
            return false;
        }
        else{
            $(this).append(data);
        }
    });

});

Test.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Helper Demo</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="JQuery.FormHelpers.js"></script>
</head>
<body>
<div class="partial"></div>
<script type="text/javascript">
    $(".partial").partial("_partial.html");
</script>
</body>
</html>

_partial.html

<ul>
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
    <li>Help</li>
</ul>

Solution

  • See the answer to this question:

    XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

    Basically, your problem is that you are running this locally, accessing a file, which breaks same-origin policy for most browsers. Your code is fine.