简体   繁体   English

从Alpacajs的后端发送功能和方案

[英]Send a function along with the scheme from backend in Alpacajs

I am having an API in backend to return the full json (schema and options) for a AlpacaJS form. 我在后端有一个API,可以返回AlpacaJS表单的完整json(模式和选项)。 The content-type of the response is application/json . 响应的内容类型为application/json Following is a sample response, 以下是示例响应,

{
  "options": {
    "fields": {
      "students": {
        "items": {
          "type": "tablerow"
        },
        "type": "table"
      }
    },
    "form": {
      "buttons": {
        "submit": {
          "click": "function(){alert(\"sample\");}"
        }
      }
    }
  },
  "schema": {
    "properties": {
      "students": {
        "items": {
          "properties": {
            "name": {
              "required": true,
              "title": "Name",
              "type": "string"
            },
            "contact-number": {
              "title": "Age",
              "type": "string"
            }
          },
          "type": "object"
        },
        "type": "array"
      }
    },
    "type": "object"
  }
}

When I click on the Submit button, I get the following error in browser console, 当我单击“ Submit按钮时,在浏览器控制台中出现以下错误,

Uncaught TypeError: t.call is not a function

I think the issue is that the function is considered as a string in the following section of the response. 我认为问题在于该函数在响应的以下部分中被视为字符串。

"form": {
  "buttons": {
    "submit": {
      "click": "function(){alert(\"sample\");}"
    }
  }
}

Is there a way in AlpacaJS to send a javascript function from backend, or is there a way to convert the function string to a javascript function in frontend? AlpacaJS中是否可以从后端发送javascript函数,或者是否可以将函数字符串转换为前端的javascript函数?

In order to get that, you should transform the stringified function to a function by doing new Function('return ' + val)(); 为了做到这一点,您应该通过执行new Function('return ' + val)();字符串化函数转换为函数new Function('return ' + val)(); (beware this is a form of eval and eval is evil ). (请注意,这是eval的一种形式,而eval是邪恶的 )。

Here's a working fiddle for that. 这是一个有用的小提琴 Tell me if it didn't work for you. 告诉我它是否对您不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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