您的位置:首页 > Web前端 > Node.js

node.js实现提交简单的form表单

2014-08-13 22:12 736 查看
Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用。Node.js借助事件驱动, 非阻塞I/O 模型变得轻量和高效,非常适合运行在分布式设备的数据密集型的实时应用(百度百科)。

简单参考互联网写了一个js提交form表单(get和post两种格式)到后台处理的程序。

js程序:

var httpserver = require("http");
var qs = require("querystring");
var url = require("url");
var fs = require("fs");   //文件流

httpserver.createServer(onRequest).listen(8081);

function onRequest(request,response)
{
var pathname = url.parse(request.url).pathname;
if(pathname=="/")	//访问表单页面
{
response.writeHead(200,{"Content-Type":"text/html"});
fs.readFile("index.html","utf-8",function(e,data){
response.write(data);
response.end();
});
}
else if(pathname=="/postlogin")	//处理post方式请求,请求路径为postlogin
{
var a="";
request.addListener("data",function(postdata){
a+=postdata;	//接收到的表单数据字符串,这里可以用两种方法将UTF-8编码转换为中文
var b = qs.parse(a);		//转换成json对象
var c = decodeURIComponent(a);		//对表单数据进行解码
console.log(a);
console.log(b);
console.log(c);
a = c;
});
request.addListener("end",function(){
response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
response.write(a);
response.end();
});
}
else if(pathname=="/getlogin")	//处理get方式请求,请求路径为getlogin
{
var a = url.parse(request.url).query;
var b = qs.parse(a);
var c = decodeURIComponent(a);

console.log(a);
console.log(b);
console.log(c);
a = c;

response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
response.write(a);
response.end();
}
else                              //如果路径不对,提示错误信息
{
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("error");
response.end();
}
}


调用的index.html的代码程序:

<!DOCTYPE html>
<html>
<head>
<title>main</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="div1" style="width: 350px;">
<form id="form1" method="post" action="postlogin" >
<fieldset>
<legend>表单1</legend>
姓名:<input type="text" name="username" /><br />
学历:<select name="education">
<option value="中学">中学</option>
<option value="大专">大专</option>
<option value="本科">本科</option>
<option value="硕士">硕士</option>
<option value="博士">博士</option>
</select><br />
住址:<input type="text" name="address" />
<input type="submit" value="提交" />
</fieldset>
</form>
</div>
</body>
</html>


最后:由于对node理解的不是太多,目前不做过多的评价,通过不断的学习,再慢慢分享自己学习的心得。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: