I have a server side Python script that returns a JSON string containing parameters for a client side JavaScript.
# Python
import simplejson as json
def server_script()
params = {'formatting_function': 'foobarfun'}
return json.dumps(params)
This foobarfun
should refer to a JavaScript function. Here is my main client side script
// 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...
}
Of course, options.formatting_function()
will complain that "a string is not callable" or something to that effect.
Upon using Chrome's Inspect Element, under the Resources tab, and navigating the left sidebar for XHR > query, I find that client_script
interprets options
as below. foobarfun
is seen as a string.
// JavaScript
options = {"formatting_function": "foobarfun"}
I would have liked client_script
to see options
as
// JavaScript
options = {"formatting function": foobarfun}
Of course, doing the following within Python will have it complaining that it doesn't know anything about foobarfun
# Python
params = {'formatting_function': foobarfun}
QUESTION:
How should I prepare my JSON string from the server side so that the client script can interpret it correctly? In this case, I want foobarfun
to be interpreted as a function object, not as a string.
Or maybe it's something I should do on the client side?