word-wrap: break-word; margin: 5px 0px; color: rgb(0, 0, 0); font-family: " sans="" font-size:="" font-style:="" font-variant-ligatures:="" a="" href="/fw/photo.html" target="_blank" :="" font-weight:="" letter-spacing:="" orphans:="" text-align:="" text-indent:="" text-transform:="" white-space:="" widows:="" word-spacing:="" -webkit-text-stroke-width:="">最近实现了Node.js当作后台,jQuery写前台AJAX代码的,实现用户登录和注册的功能,刷新了前后端交互的三观。特记录一下。
1.login.ejs实现form框架
代码如下
form不加method,意图自己用ajax发送请求。
2.js实现request的发送
代码如下
$("#login_submit").click(function(){
varusername=$('#username').val();
varpassword=$('#password').val();
//这里实现对 username和password格式的判断
//........
//发送ajax请求 使用post方式发送json字符串给后台login
$.ajax({
type:"post",
url:"http://localhost:3000/login",
dataType:"json",
data:{ username: username, password: password },
success:function(data){
//接受返回的数据,前端判断采取的动作
if(data){
if(data.message=="false"){
alert('密码错误,请重新输入');
window.location.href="login";
}else{
alert('登陆成功');
window.location.href="index";
}
}else{
}
}
});
});
2.后台接收
代码如下
/**
* 注册页 post
*/
router.post('/reg',function(req, res, next) {
//先查询有没有这个user
console.log("req.body"+req.body);
user2.findDocuments(DATABASE,"users", 1, {"uName":req.body.username},function(user) {
res.setHeader('Content-Type','application/json;charset=utf-8');
if(user.length==0){
//用户名没有重复 同意创建用户
user2.insertDocuments(DATABASE,"users",
[{
"uName":req.body.username,
"uPasswd":req.body.password,
"uEmail":req.body.email,
"uHasshop":0,
"uShopname":"null",
"aId":'-1'
}],
function(result){
res.send({status:"success", message:"true"});
}
);
}
else{
// 用户名重复。找到这个user 不同意创建用户
res.send({status:"success", message:"false"});
}
});
});
注册页面跟登陆页面类似。不再赘述。
总之呢,之前老是觉得自己浏览器访问的页面是前端的东西。后端是一个虚无缥缈的一堆代码。现在明白其实访问的所有的url都是属于后端的。后端发送什么内容,浏览器就显示什么内容。前端的显示只是一时半刻,后端的资源才是永久哒。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助。
【node.js jquery实现用户登录】node.js+jQuery实现用户登录注册AJAX交互方法
http://m.bbyears.com/wangyezhizuo/126728.html
推荐访问: