weixin_33737134 2017-01-09 09:52 采纳率: 0%
浏览 25

通过AJAX发送js函数

I would like to pass "a javascript function" to my backend and I'm using ajax. This is a short example:

var data = { 
    prop: function (e) { alert(e) }
};
ajax.(..., data: data, dataType: "json")...

This automatically removes the prop from the data because it's a function.

How can I pass this function to my backend with json? Without converting it to a string.

  • 写回答

2条回答 默认 最新

  • larry*wei 2017-01-09 09:58
    关注

    You really don't want to send a function from the client to the server and execute that function on the server, not without a lot of security checks. Think about it for a moment, remembering that you can't trust anything you receive from the client. Separately, the server should already know how to do the things it needs to do; usually what you'd do instead is send a command (a string) telling it to use that function (which it would already have, and thus you could trust).

    But, if you want to go ahead and do that anyway:

    Without converting to string.

    You can't. The only way is to send the function as source code or some other form that can be sent via HTTP, which is ultimately a text-based protocol. So you'd send source code, or you'd compile it to some kind of bytecode of your own devising and then send that (converted to a string, probably Base64 or similar), etc.

    As of ES2015, normal functions are required to have a toString that takes the form of a valid function declaration or expression, so you could send that string:

    var dataToSend = {prop: data.prop.toString()};
    ajax(..., data: JSON.stringify(dataToSend), dataType: "json")
    

    The server would then have to compile that string and execute the result. JavaScript provides a way to do that (eval), but again: It's very dangerous to execute code received from the client. Doing very dangerous things requires doing a lot of safety checks first.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog