简体   繁体   English

在Sails.js中将值从后端发送到前端,并使用EJS进行检查

[英]Send value from backend to frontend in Sails.js and check with EJS

I'm trying to submit data from a form, then from the controller there are 3 possibilities, it already exists, the data is wrong and it was successfully created. 我正在尝试从表单提交数据,然后从控制器提交了3种可能性,它已经存在,数据错误并且已成功创建。 Then I want to return a value to the front-end, let's say everything is ok and I return {result: 0}. 然后,我想向前端返回一个值,假设一切正常,然后返回{result:0}。 Then using ejs I'll check the value of 'result' and if it's a 0 I want to call a (front-end) javascript function. 然后使用ejs来检查“结果”的值,如果它是0,我想调用一个(前端)javascript函数。

EJS: EJS:

<html>
  <head>
    <script src="functions.js">
  </head>
  <body>
    <form action="/test" method="POST">
      <input type="text" name="data" />
      <button>Send</button>
    </form>
    <div id="message">
      <% if (typeof result !== 'undefined' && result === 0){ %><script>showMessage();</script><% } %>
    </div>
  </body>
</html>

Javascript (front-end) Javascript (前端)

function showMessage() {
  document.getElementById('message').innerText = "sometext";
}

Javascript (back-end) Javascript (后端)

module.exports = {
  postData: function (req, res) {
    Data.findOne({data: req.param('data')}).exec(function (err, data) {
      if (err) {
        return {result : 1};
      }
      if (data) {
        return {result: 2};
      }
      if (!data) {
        Data.create({data: req.param('data')}, function (err, data) {
          if (err) {
            return {result: 1};
          }
          return {result: 0};
        });
      }
    });
  }
}

I know how to send data using res.view(), but I don't want to reload the page again I just want to send something to the frontend and make some action. 我知道如何使用res.view()发送数据,但是我不想再次重新加载页面,我只想向前端发送一些内容并执行一些操作。

Thank you for your time. 感谢您的时间。

Your best bet is to include the Javascript script you want to execute inline. 最好的选择是包括要内联执行的Javascript脚本。 Then, you can use a conditional EJS clause to include your script if the result is equal to 0. 然后,如果结果等于0,则可以使用条件EJS子句包含脚本。

<% if (result == 0) { %>
    <script type="text/javascript">
        /* Your Function Here */ 
    </script>
<% } %>

You can store variables in the backend eg. 您可以将变量存储在后端,例如。 someVariable = "some value"

Then in your frontend call <%- someVariable %> 然后在您的前端调用<%- someVariable %>

OR save it as an object in the backend eg. 或者将其另存为对象,例如后端。

vehicle.car = {
    manufacturer: 'Holden',
    make: 'Colorado',
    year: '2018'
}

THEN in the frontend call the object model eg. 然后在前端调用对象模型,例如

<p>Your <%- vehicle.car.year %> <%- vehicle.car.manufacturer %> <%- vehicle.car.make %>...

A use case example is to show the current year of copyright of a footer partial that persist page requests. 一个用例示例是显示保留页面请求的页脚部分的当前版权年份。

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

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