How to send additional javascript code to client from nodejs server after page load

守給你的承諾、 提交于 2019-12-11 14:57:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!