Skip to content Skip to sidebar Skip to footer

How To Load Data From Another File As An Option Value In Javascript / Jquery?

Consider the below code: $('.sceditor').sceditor({ emoticons: // contents from another file here }); I want to load another file which contains a JSON object as the value of t

Solution 1:

I would use the .done() and .always() promise methods on the jqxhr object to accomplish this.

It sounds like what you want is to initialize the sceditor regardless of whether you have emoticons or not. However, if you are able to load emoticons then you want to use those.

Here is a quick solution showing how to use the promise methods to achieve what you want. Obviously you can expand and make this better, but this can serve as a starting point.

// create a variable to store the resultsvar emoticons = false;

    $.getJSON('../../images/emoticons/default/emoticons.json')
    .done(function(result){
        emoticons = result;
    })
    .always(function(){
        // always initialize the sceditor
        $('.my-selector').sceditor({emoticons: emoticons}); 
    });

And the requisite jsFiddle: http://jsfiddle.net/oLspfLby/1/

Solution 2:

You can define variable in outer scope, fill it in getJSON response function and use in further code

var foo;
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
    foo = response;
});

$(".sceditor").sceditor({
    emoticons: foo
});

Post a Comment for "How To Load Data From Another File As An Option Value In Javascript / Jquery?"