I am working on a server-side Python script that generates a JSON string with parameters for a JavaScript function on the client side.
# Python
import simplejson as json
def server_script()
params = {'formatting_function': 'foobarfun'}
return json.dumps(params)
The foobarfun
I am referring to is expected to be a JavaScript function. Here is the primary client-side script I have:
// JavaScript
function client_script() {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, async=true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
options = JSON.parse(xhr.responseText);
options.formatting_function();
}
};
xhr.send(null);
}
function foobarfun() {
//do_something_funny_here...
}
However, when I try to call options.formatting_function()
, I receive an error stating "a string is not callable" or something similar.
Upon inspecting the elements in Chrome's DevTools under the Resources tab and analyzing the XHR response, it appears that client_script
interprets options
like this:
// JavaScript
options = {"formatting_function": "foobarfun"}
What I actually want is for options
to be interpreted as:
// JavaScript
options = {"formatting function": foobarfun}
Unfortunately, if I try assigning
params = {'formatting_function': foobarfun}
in Python, it does not recognize the foobarfun
function.
Issue:
How can I structure my JSON string from the server so that the client script will interpret it correctly? Specifically, I want foobarfun
to be treated as a function object instead of a string.
Do I need to make changes on the client side for this to work properly?