简体   繁体   中英

Send js function through AJAX

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.

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.

Current JavaScript versions ie < ES2015 doesn't natively support this through the use of functions such as JSON.stringify() or similar, although there is a package which you can install if you're using NPM or another package manager for modules.

This package is called serialize-javascript which adds a serialize function that you can use to convert functions, regexes etc. to a string representation. You could then use eval on the server-side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM