【问题标题】:Is it possible return an function with AJAX?是否可以使用 AJAX 返回一个函数?
【发布时间】:2022-12-03 01:22:03
【问题描述】:

假设我需要对我的服务器进行 ajax 调用

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){}
});

作为服务器的响应,我回复了一些 javascript 代码

res.send("const myFunc = (b) => { console.log(b) }");

有没有办法做这样的事情?:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){ 
        response('hello'); //I would like 'hello' to appear in the console
    }
});

【问题讨论】:

  • evalnew Function
  • @Konrad 我可以阅读文档并查看一些示例的任何来源?
  • @DmytroV ... OP 是否听说过MDNs 文档及其JavaScript documentation? ... evalFunction 其中后者 new Function 被认为是一种 evaluation。
  • 顺便说一句,值得阅读整个 MDN 文档,您可以通过这种方式轻松学习新事物

标签: javascript ajax


【解决方案1】:

Function() constructor 示例:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){
        const fn = new Function('x', `${response}; myFunc(x)`)
        fn('hello')
    }
});

请注意,您必须在字符串内运行函数,因此 ${response}; myFunc(x)

以下是其工作原理的示例:

const code = 'const myFunc = (b) => { console.log(b) }'
const fn = new Function('x', `${code}; myFunc(x)`)
fn('Hello')

如果您像这样发送数组可能会更容易:

res.send("b", "console.log(b)");

然后你可以像这样使用它:

$.ajax({
    type: 'POST', 
    url: 'url/url', 
    success: function(response){
        const fn = new Function(...response)
        fn('hello')
    }
});

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2014-10-23
    • 1970-01-01
    • 2017-10-09
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多