将任意数量的参数传递给JavaScript函数 [英] Pass an arbitrary number of parameters into a JavaScript function
问题描述
我的JavaScript代码几乎不是一个Ajax请求,它期望从后端返回XML.后端可以将 execute_callback
作为以下XML标签之一返回:
My JavaScript code is barely an Ajax request that expects XML to be returned from back-end. The back-end can return execute_callback
as one of XML tags like this:
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
</execute_callback>
</response>
只要您知道此回调
期望的确切参数数量,一切都可以.但是如果后端返回了该怎么办
And everything is okay as far as you know the exact number of parameters this callback
expects. But what if the back-end has returned
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
<param>10.2</param>
<param>some_text</param>
</execute_callback>
<execute_callback>
<function_name>otherFunction</function_name>
<param>{ x: 1, y: 2 }</param>
</execute_callback>
</response>
我现在如何将参数10.2和'some_text'传递给 someFunction
和JSON {x:1,y:2}传递给 otherFunction
?
How do I now pass parameters 10.2 and 'some_text' to someFunction
and JSON { x: 1, y: 2 } to otherFunction
?
我知道一个丑陋的解决方案(使用函数的 arguments
),但是我正在寻找一个漂亮的解决方案.
I know an ugly solution (using function's arguments
), but I am looking for a pretty one.
在我忘记之前:不要为我解析XML-我可以自己做:)我所需要的只是某种技巧,可以将任意数量的参数传递给JavaScript中的函数.如果您知道 Python ,我想要:
And before I forget: don't parse the XML for me - I can do that on my own :) All I need is somewhat of a trick to pass an arbitrary number of arguments to a function in JavaScript. If you know Python, I want:
def somefunc(x, y):
print x, y
args = { 'x' : 1, 'y' : 2 }
somefunc(**args)
但使用JavaScript.
but in JavaScript.
推荐答案
您可以参考 Function.apply .假设在全局对象(浏览器中的 window
)中声明了回调函数.
You could refer to Function.apply. Assuming the callback functions are declared in global object (window
in browser).
var callback_function = window[function_name];
if (callback_function) { // prevent from calling undefined functions
callback_function.apply(window, params); // params is an array holding all parameters
}
这篇关于将任意数量的参数传递给JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!