Vini
Vini

Reputation: 977

Not able to load the script file inside another script file

Not able to load the script file inside another script file when using $.getJson(); inside the loaded script files.

Consider fisrt.html:

<script>
$.getScript("second.js",function(){
     // some code here
});
</script>

my second js file is like: second.js:

$.getJSON("somefile.json",function(){
});

When remove the $.getJSON from the second.js the files load perfectly without any problem.

How can I load the my json file with $.getJSON?

EDIT:

complte json calling:

$.getJSON('js/offline.json', function(data) {
            alert("success");

        }.error(function(data){
            alert(JSON.stringify(data));
        });

Upvotes: 0

Views: 62

Answers (2)

Ilia Choly
Ilia Choly

Reputation: 18557

You're trying to use the promise and standard callback API at the same time. Here's what you want.

$.getJSON("js/offline.json")
  .done(function (data) {
    alert(data);
  })
  .fail(function (err) {
    alert(err);
  });

Upvotes: 1

ArinCool
ArinCool

Reputation: 1738

You can try using the following function:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

Also: 1. Remove the : in the second script to replace with ; 2. make sure that somefile.json exists in the same directory.

Upvotes: 1

Related Questions