簡體   English   中英

Meteor將數據從客戶端傳遞到服務器

[英]Meteor pass data from client to server

我有一個注冊表單,當用戶單擊提交按鈕時,每個文本框中的值將被發送到服務器以插入該數據,並返回true / false。

客戶:

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

服務器:

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

結果證明不起作用。 怎么解決這個? 很多人說“使用發布/訂閱”,但我不明白如何使用它。

首先,觀看介紹性截屏視頻並閱讀文檔的數據和安全性部分。

發布/訂閱模型中的代碼如下所示:

共同:

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

客戶:

Meteor.subscribe("messages");

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

服務器:

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

另一種解決方案是使用Meteor.call('yourMethodName') (在客戶端上)。

然后,在服務器上,您可以擁有

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

您可以考慮將會話變量設置為返回值。

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

然后在一些模板中......

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

為什么這一切?

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".

顯然,這種方法破壞了訂閱/發布模型的價值,它只應用於不需要實時數據的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM