user1573618
user1573618

Reputation: 1816

Load a javascript object with its functions from file

In a website I would like to use a javascript function to load an object from a file. I initially tried using JSON but my javascript object is complex and has functions for some parameters. Is there a way I can load the object from a file?

myObject.js (not valid JSON as it has a function)

{
    "value1": "some value",
    "functionValue": function() { 
        return "function value"; 
    }
}

function to load object from file

function getFileObject(fileURL) {
    var myObject;

    $.ajax({
        url: fileURL,
        type: "GET",
        datatype: 'json',
        async: false,
        success: function (result) {
            myObject = result;
        }
     });

     return myObject;
}

Upvotes: 1

Views: 1191

Answers (2)

Darian Lewin
Darian Lewin

Reputation: 182

Have you tried to import myobject.js using the

<script src="myobject.js" type="text/javascript"/>

tag in the header of your web page and assigning the object in the myobject.js file to a variable which you can use in the other .js file?

This should work for a single file (I have not tested it myself), but if you want to import your file dynamically at the client side, the solution from @dystroy might be more suitable.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

If you really have to pass a function implementation, simply don't use JSON and eval your text.

function fetchFileObject(callback) {
    $.ajax({
        url: value,
        type: "GET",
        datatype: 'text',
        success: function (result) {
            var myObject = eval('('+result+')');
            callback(myObject); // do something  with myObject
        }
     });

}

But... that's not something I'd consider myself.

Beware that you really shouldn't use async: false. It's now deprecated and there never was any good reason to use it. That's the reason why I refactored your code to accept a callback.

Upvotes: 1

Related Questions