2

please check this:

    var scripts = {};

require = function(src){
    var id = Math.round(+new Date()/1000);

    $.ajax({
        url: src + '.json',
        type: 'GET',
        dataType: "json",
        cache: false,
                    async: false,
        success : function(data){
            scripts[id] = data;
        }
    });

    return scripts[id];
}

return undefined :/ What is the problem!? i don't know...

EDIT! 'async : false' and run!

2
  • Of course we know what JSON is. The error here has to be on the server side. Is youe src valid? Commented Oct 1, 2012 at 5:18
  • Try to use XMLHttpRequest object instead of jquery. It'll block. Commented Oct 1, 2012 at 5:44

4 Answers 4

3

It is because $.ajax is asynchronous in your call.

return scripts[id];

The above line is executed even before the success callback is triggered.

Sign up to request clarification or add additional context in comments.

Comments

1

it is a asynchronous call. scripts is empty when you return.

to verify the cause,

window.scripts = {};

require = function(src){
var id = Math.round(+new Date()/1000);

$.ajax({
    url: src + '.json',
    type: 'GET',
    dataType: "json",
    cache: false,
    success : function(data){
        window.scripts[id] = data;
        alert(window.scripts)
    }
});

//return scripts[id];

}

after alert, see the value of window.scripts

Comments

0

its async issue .. Ajax call is called asynchrnously.

return scripts[id];

is executed before ajax call return.s

Comments

0

Your problem is that the call is asynchronous. This means that your method is returning before the call is finished.

Instead of returning the scripts[id] try this instead:

require = function(src){
    var id = Math.round(+new Date()/1000);

    $.ajax({
        url: src + '.json',
        type: 'GET',
        dataType: "json",
        cache: false,
        success : function(data){
            scripts[id] = data;
            DoStuff(scripts[id]);
        }
    });
}

DoStuff(data) {
    // do whatever it is you were going to do after the return.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.