How to get json data from separate js file to js main file

In my project, I wanted to save the data separately from the templates and the main.js. For instance,

in my data.js:

define({ heading: "Some Heading", subHeading : "Subheading is cool" }); 

in my main.js,

 require(['jquery', 'data'], function($, data){ console.log("data object is :" + data); ); 

This works, and I get the intended result on the console. Similarly, I wanted to make an api call and get json data to update the data.js data as shown below,

 define(function(){ require(["http://some api url.com?apikey=apikey&callback=define"], function (someData) { return someData; } ); }); 

but I do not get json data on main.js from the API call, I get " data object: undefined ".

I am not sure how to get "someData" in the main.js.

Any help pointing to a possible fix is ​​much appreciated. Thanks.

+4
source share
3 answers

You cannot make server calls and upload files via requireJS. You must use ajax calls to do this. You can use the getJSON jQuery method. For instance.

 $.getJSON("http://some api url.com?apikey=apikey",function (someData) { //perform the calculations needed with someData here console.log(someData); }); 
+2
source

Thanks to everyone for hitting my problem! I managed to get this working using the async plugin. Basically, I sent my problem to a Google group and I got a response, here is the URL for more information, https://groups.google.com/forum/?fromgroups=#!topic/requirejs/39rieY2ZovE

Hope this helps everyone.

Thanks. radiant

+1
source

Check out the RequireJS plugins .

For JSON data, you change the request to

 require([`json!http://some api url.com?apikey=apikey&callback=define`], function(someData){ // do something }); 
0
source

All Articles