My web app (running jQuery) gets the following JSON response from the server:
{
"script_0": "$('#objview_0_306').on('click', function(e){ getObjectResponse(96089, '306', 'display'); e.preventDefault();});",
"verb_0": "display",
"obid_0": "0_306",
"body_0": "<div id=\"objview_0_306\"></div>",
"icon_0": "icons/caseman16.png",
"close_0": "previousTab();",
"title_0": "Cases",
"cmdCount": "1"
}
The script_0 element contains scripts that must be run, in this case adding an onClick event to a DOM element.
At the moment, I use eval() to run the scripts, since they are returned as strings. Is there a way to avoid using eval()?
Noop. The eval (and alias Function constructor etc.) is designed to do exactly this, parse strings into runnable javascript.
If you don’t want to use
eval, instead of return the complete javascript from the server, you can return values in json response that instruct your client app to do predefined tasks.I’m going to plagiarize the comment made by @Esailija:
Why on earth would you have code in json? it’s a data-interchange format…