html - 用ajax提交表单后,返回验证数据在页面location.href跳转到主页,怎么传递session给主页
ringa_lee
ringa_lee 2017-04-17 15:32:28
0
2
518
app.post('/user/signin',function(req,res){
    var user=req.body.user;
    var {name,password}=user;

    User.findOne({name:name},function(err,user){
        if(err) console.log(err);
        if(!user) return res.json({state:1});

        user.comparePassword(password,function(err,isMatched){
            if(err) console.log(err);
            if(isMatched) {
                res.json({state:3});
            }
            else res.json({state:2});
        });

    });
});

$('#signinModal .btn-success').on('click',function(e){

$.ajax({
    type:'POST',
    url:'/user/signin',
    data:$('#signinModal form').serialize(),

    success:function(data){
        switch(data.state){
            case 1:$('#errorName').css({opacity:1});break;
            case 2:$('#errorPassword').css({opacity:1});break;
            case 3:location.href='/';break;
            }
        }
    });

});

ringa_lee
ringa_lee

ringa_lee

reply all(2)
Ty80

You can assign user information to req.session.user through req.session.user = userInfo
When you jump to the homepage, you can get user information through req.session.user.
If your front-end page needs it, you can pass the value during rendering, such as

res.render('index',{
    user: req.session.user
});

If you are using the express framework, you can use res.locals.user = req.session.user;
In this way, your page can be obtained directly by using the user variable, such as:

<p class="menu">
        <% if (user) { %>
          <a class="item" href="/posts?author=<%= user._id %>">个人主页</a>
          <p class="pider"></p>
          <a class="item" href="/posts/create">发表文章</a>
          <a class="item" href="/signout">登出</a>
        <% } else { %>
          <a class="item" href="/signin">登录</a>
          <a class="item" href="/signup">注册</a>
        <% } %>
      </p>
洪涛

(Take the java backend as an example) After the front-end ajax submits the form (var loader = new net.AjaxRequest(url, deal_data, onerror, "POST", params);) [Note: net.AjaxRequest is a predefined function, where deal_data is the callback processing function after the ajax request is successful], the backend performs business After processing, use JSONArray to place the results to be returned, write httpservletresponse into it, and return it to the front end,

JSONArray jsonArray = new JSONArray();
jsonArray.add(0, true);
response.getWriter().print(jsonArray);

Processed by the ajax callback function: get the return text, parse it into json data, and process it as needed.

var datas = eval(this.req.responseText);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template