【问题标题】:run javascript function from string variable and pass parameters从字符串变量运行javascript函数并传递参数
【发布时间】:2012-09-19 08:41:24
【问题描述】:

我需要从我的 costom jquery 插件中调用用户定义的 javascript 函数并将参数传递给它,例如:

function test(data)
    {
      var myfunc="function(data){alert(data);}"; //this is user defined function I   retrieved from html tag attribute
      var fn=new Function("("+myfunc+")();");
      fn.apply(this,arguments);
      return fn;
} 
test("hello");

结果未定义,如何将数据参数从测试函数传递到用户定义函数?提前致谢!

问题更新:

我正在写一个jquery插件来处理ajax请求,很像asp.net mvc unobtrusive ajax,我从html标签attrbute得到ajax callfack函数,例如:

<div data-ajax-success="function(data,status,xhr){alert(data);}"....

data-ajax-success 属性的值是用户定义的函数,可以是以下格式:

data-ajax-success="function(data,status,xhr){alert(data);}"
data-ajax-success="function(data){alert(data);}"
data-ajax-success="function(){alert('hello');}"
data-ajax-success="functionName"

我需要将此属性值解析为javascript函数并将jquery ajax回调参数传递给该函数,其中data-ajax-success值为函数名称,我可以使用Micrsoft jquery-unobtrusive-ajax中定义的以下方法正确调用它.js:

function getFunction(code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        }
        argNames.push(code);
        return Function.constructor.apply(null, argNames);
    }

但是当 data-ajax-success 是函数体时,我无法将参数传递给它,这是我处理 ajax 回调的示例代码:

loadData: function (index, options) {
complete: function (xhr,status) {
            $(context.loading).hide(context.loadingDuration);
            getFunction(context.onComplete, ["xhr", "status"]).apply(this, arguments);
            },
        success:function (data, status, xhr) {
            $(context.updateTarget).html(data);
            getFunction(context.onSuccess, ["data", "status", "xhr"]).apply(this, arguments);
            },
            error: getFunction(context.onFailure, ["xhr", "status", "error"])
});

      $.ajax(options);
  }

有人可以帮助我吗?非常感谢!

【问题讨论】:

  • 您能更详细地解释一下字符串"function(data){alert(data);}" 的来源吗?
  • this 有帮助吗? (使用eval
  • 我能否首先指出总体而言,这看起来是个非常糟糕的主意,您可能做错了。

标签: javascript jquery function jquery-callback


【解决方案1】:

MDN 描述 Function 对象的语法如下:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

下面是对应的例子:

// Example can be run directly in your JavaScript console

// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// > 8

应用于您的示例代码,它应该是:

var fn=new Function("data",myfunc);

参考:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function

【讨论】:

    【解决方案2】:

    您没有将参数传递给fn 函数。

    改变这部分:

    var fn=new Function("("+myfunc+")();");
    

    到这里:

    var fn=new Function("("+myfunc+")("+data+");");
    

    但是如果你要像这样定义函数,data 变量必须包含一个 json 字符串:

    var fn=new Function("("+myfunc+")("+JSON.stringify(data)+");");
    

    【讨论】:

      【解决方案3】:
      【解决方案4】:

      我通过修改这个microsoft方法解决了:

        function getFunction(code, argNames) {
          var fn = window, parts = (code || "").split(".");
          while (fn && parts.length) { fn = fn[parts.shift()]; }
          if (typeof (fn) === "function") { return fn; } //onSuccess="functionName"
          if ($.trim(code).toLowerCase().indexOf("function")==0) { return new Function("return (" + code + ").apply(this,arguments);");} //onSuccess="function(data){alert(data);}"
          argNames.push(code);
          try {return Function.constructor.apply(null, argNames); //onSuccess="alert('hello');return false;"
          }catch(e){alert("Error:\r\n"+code + "\r\nis not a valid callback function");}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-20
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 2020-01-01
        相关资源
        最近更新 更多