Meteor pass data from client to server

混江龙づ霸主 提交于 2019-12-17 22:28:08

问题


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.

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.


回答1:


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();
});



回答2:


An alternative solution is to use Meteor.call('yourMethodName') (on the client).

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.



来源:https://stackoverflow.com/questions/20630829/meteor-pass-data-from-client-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!