nodejs 静态资源文件与登陆交互

server2.js

var express=require('express');
var expressStatic=require('express-static');

var server=express();
server.listen(63342);

//用户数据
var users={
  'mike': '123456',
  'jack': '654321',
  'luci': '987987'
};

server.get('/login', function (req, res){
  var user=req.query['user'];
  var pass=req.query['pass'];

  if(users[user]==null){
    res.send({ok: false, msg: '此用户不存在'});
  }else{
    if(users[user]!=pass){
      res.send({ok: false, msg: '密码错误'});
    }else{
      res.send({ok: true, msg: '成功'});
    }
  }
});

server.use(expressStatic('./www'));

a.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="ajax.js" charset="utf-8"></script>
    <script type="text/javascript">
    window.onload=function (){
      var oUser=document.getElementById('user');
      var oPass=document.getElementById('pass');
      var oBtn=document.getElementById('btn1');

      oBtn.onclick=function (){
        ajax({
          url: '/login',
          data: {user: oUser.value, pass: oPass.value},
          success: function (str){
            var json=eval('('+str+')');
            if(json.ok){
              alert('登录成功');
            }else{
              alert('登录失败:'+json.msg);
            }
          },
          error: function (){
            alert('不好意思,失败了');
          }
        });
      };
    };
    </script>
  </head>
  <body>
    用户:<input type="text" id="user" /><br>
    密码:<input type="password" id="pass" /><br>
    <input type="button" value="登录" id="btn1" />
  </body>
</html>

ajax.js

function json2url(json){
    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    }
    return arr.join('&');
}
function ajax(json){
    json=json || {};
    if(!json.url)return;
    json.data=json.data || {};
    json.type=json.type || 'get';

    var timer=null;

    if(window.XMLHttpRequest){
        var oAjax=new XMLHttpRequest();
    }else{
        var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
    }

    switch(json.type){
        case 'get':
            oAjax.open('GET',json.url+'?'+json2url(json.data),true);
            oAjax.send();
            break;
        case 'post':
            oAjax.open('POST',json.url,true);
            oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            oAjax.send(json2url(json.data));
            break;
    }

    oAjax.onreadystatechange=function(){
        if(oAjax.readyState==4){
            clearTimeout(timer);
            if(oAjax.status>=200 && oAjax.status<300 || oAjax.status==304){
                json.success && json.success(oAjax.responseText);
            }else{
                json.error && json.error(oAjax.status);
            }
        }
    };
}

截图:

 

效果:

 

posted @ 2017-11-06 23:57  1点  阅读(327)  评论(0编辑  收藏  举报