简体   繁体   English

Meteor将数据从客户端传递到服务器

[英]Meteor pass data from client to server

I have a registration form, and when the user clicks the submit button the value in every textbox will be sent to server to insert that data, and return true/false. 我有一个注册表单,当用户单击提交按钮时,每个文本框中的值将被发送到服务器以插入该数据,并返回true / false。

Client: 客户:

Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          var isSuccess = insertMsg(email,msg);
          if(isSuccess){
             alert("Success");
          }else alert("Try again");
    }
});

Server: 服务器:

function insertMsg(email,msg){
     Messages.insert({Email:email,Message:msg});
     return true;
}

This turned out to not work. 结果证明不起作用。 How to solve this? 怎么解决这个? Many people said "use publish/subscribe", but I don't understand how to use that. 很多人说“使用发布/订阅”,但我不明白如何使用它。

First, watch the introductory screencast and read the Data and security section of the docs. 首先,观看介绍性截屏视频并阅读文档的数据和安全性部分。

Your code in a publish/subscribe model would look like this: 发布/订阅模型中的代码如下所示:

Common: 共同:

Messages = new Meteor.Collection('messages');

Client: 客户:

Meteor.subscribe("messages");

Template.cust_register.events({
    'click button': function(){
          var email = $('#tbxCustEmail').val();
          var msg = $('#tbxCustMsg').val();
          Messages.insert({Email:email,Message:msg});
    }
});

Server: 服务器:

Meteor.publish("messages", function() {
    return Messages.find();
});

An alternative solution is to use Meteor.call('yourMethodName') (on the client). 另一种解决方案是使用Meteor.call('yourMethodName') (在客户端上)。

Then, on the server, you can have 然后,在服务器上,您可以拥有

Meteor.methods({
    yourMethodName: function() { /* validate input + return some data */ }
});

You can consider setting a session variable to the return value. 您可以考虑将会话变量设置为返回值。

Meteor.call('yourMethodName', function (err, data) {
    if (!err) {
        Session.set('myData', data);
    } 
});

And then in some some template... 然后在一些模板中......

Template.whatever.helpers({
    messages: function() {
        return Session.get('myData');
    }
});

Why do all this? 为什么这一切?

1) You can explicitly deny all direct `insert/update/find` queries from the client, and force usage of pre-defined Meteor methods.

2) You can manually determine when certain data is "refreshed".

Obviously, this methodology undermines the value of the subscription/publication model, and it should only be used in cases where real-time data isn't required. 显然,这种方法破坏了订阅/发布模型的价值,它只应用于不需要实时数据的情况。

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

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