2012-04-11 87 views
4

這裏是一個職位HTML表單:獲取發佈數據從形式

<html> 
<body> 
<h1>Home Html Page</h1> 
<a href="/Product/Index">Go To Product</a> 
<hr/> 
<form action="/Home/Index" method="POST" name="form1"> 
    Enter Text: 
    <input type="text" id="txtInput"/> 
    <button id="btnPost">Post Data</button> 
</form> 
</body> 
</html> 

下面是JavaScript代碼,這應該得到發佈的數據:

function Server(req, resp) { 
    if (req.method == 'POST') { 
     var chunk = ''; 
     req.on('data', function (data) { 
      chunk += data; 
     }); 
     req.on('end', function() { 
      console.log(chunk + "<-Posted Data Test"); 
     }); 
    }' 

    ... 

    resp.write(...); 
    resp.end(); 
} 

你能幫助我嗎?我是nodejs中的新手,那麼你能告訴我一個例子嗎?

+0

那是相當多的代碼,我有(其中我沒有用,所以我不能評論它的價值)你看到了什麼問題? – ControlAltDel 2012-04-11 19:40:44

回答

10

你有你的<input>元素指定一個name這樣的:

<input name="txtInput" type="text" id="txtInput"> 

只有那些name集才能發佈。

例子:

var http=require('http'); 
var util=require('util'); 
var querystring=require('querystring'); 

var server=http.createServer(function(req,res){ 
    if (req.method=='GET'){ 
     res.end('<form action="/Home/Index" method="POST" name="form1">Enter Text:<input name="txtInput" type="text" id="txtInput"/><button type="submit" id="btnPost">Post Data</button></form></body></html>'); 
    }else{ 

     var chunk = ''; 
     req.on('data', function (data) { 
      chunk += data; 
     }); 
     req.on('end', function() { 
      console.log(chunk + "<-Posted Data Test"); 

      res.end(util.inspect(querystring.parse(chunk))); 
     }); 

    } 
}).listen(8080); 

爲了解析FORMDATA只是(在上面的例子一樣)使用querystring.parse(str, [sep], [eq])

例子:

querystring.parse('foo=bar&baz=qux&baz=quux&corge') 
// returns 
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' } 
+0

謝謝。我很感謝你的回答,這很清楚。 – karaxuna 2012-04-11 21:21:17

+0

不客氣:) – stewe 2012-04-11 21:23:07