问题
When a popup shows up on my website, I want the div in that popup rendered one of many different ways depending on what a certain chosen setting is. Ideally, I'd want a button pressed to open the popup, have the client ask the server for the code it needs based on what the current setting is, then once it gets the code from the server execute it and render the contents of the popup.
Do I require the code on the server, save the functions as properties on an object, and send the object to the client? Not sure if some of the functions would throw an error because DOM-related functions won't compile on a server?
Do I send the functions as a file and have the client require it on the client-side using a library like require.js or browserify?
回答1:
I would use eval() to solve your problem.
Using Ajax on client :
$.ajax({
url:'MyServer/code.json',
success : function(data, code) {
eval(data.code);
}
});
MyServer/code.json
{
"code":"alert('Code from server executed.'); $('body').css({ 'background-color': '#000'});"
}
This is a simple example with JSON and this is not secure at all. Be carefull using eval()
.
来源:https://stackoverflow.com/questions/51850397/how-to-send-additional-javascript-code-to-client-from-nodejs-server-after-page-l