2016-03-24 12 views
0

在下面的代碼中,我根據用戶請求顯示以下HTML文件。我也想在我的app.js文件的app.post()函數中訪問clubname和type datavalues。如何在使用快遞時訪問表單中的ejs數據

<!DOCTYPE html> 
<html> 
<head> 
    <title><%= title %></title> 
    <link rel='stylesheet' href='/stylesheets/style.css' /> 
</head> 
<body> 
<% include templates/adminheader.ejs %> 
<h1>Respond to Club Requests</h1> 

<form name="clubform" method="post"> 
    <% for (var i in clubreq){%> 
     Club Name:<%= clubreq[i].clubname %><br><br>//I want to access this variable in my app.post() function 
     Club Type:<%= clubreq[i].type %><br><br> 
     <input type="submit" value="accept"/><br><br><hr> 
    <%} %> 
</form> 

</body> 
</html> 

app.js。在這裏,我根據用戶請求呈現HTML文件

app.get('/clubreq', function(req, res, next){ 
     res.render('clubreq', { 
      title: 'Club Requests', 
      "clubreq" : docs 
     });  
}); 
app.post('/clubreq', function(req, res, next){ 
    //I want to access clubname and type datavariables here and store it in my mongodb database 
}); 
+0

是俱樂部名稱和類型的變量所呈現的純文本或文本里面輸入。另外,app.post()代碼實際上並不是客戶端,是嗎? –

+0

是的,我希望這兩個變量被呈現爲純文本 –

+0

如果您想在提交表單時訪問值服務器端,則需要將它們放入輸入元素中。您可以選擇文本類型或隱藏文本,但除非將值嵌入到有效的表單字段值中,否則app.post()將無法訪問這些值。 –

回答

1

讓我們從獲取表單中的信息開始。編輯表單,像這樣:

<form action="/clubreq" method="post"> 
    <% for (var i in clubreq){%> 
     Club Name: <input type="text" name="clubname[]" value="<%= clubreq[i].clubname %>" /><br><br> 
     Club Type: <input type="text" name="clubtype[]" value="<%= clubreq[i].type %>" /><br><br> 
     <input type="submit" value="accept"/><br><br><hr> 
    <%} %> 
</form> 

重要的點被添加指示在何處提交表單以及加入的投入,以確保該值,並與形式運輸的action屬性。如果您不喜歡它的外觀,可以將輸入類型更改爲隱藏,然後添加另一個回聲,就像以前的俱樂部名稱和俱樂部類型一樣,供最終用戶查看。

現在到如何訪問表單數據的服務器端,以下內容添加到您的所有其他中間件頂部:

app.use(express.bodyParser()); 

接下來,您可以訪問後的數據在你的方法,像這樣:

app.post('/clubreq', function(req, res, next){ 
    // req.body object has your form values 
    console.log(req.body.clubname); 
    console.log(req.body.clubtype); 
}); 

希望幫助

相關問題