首先,我有一个由我设计的网站,因为我是一名前端设计师 . 我有后端服务器的API,由其他人创建 .

我已成功发出请求并从服务器回复了auth令牌并创建了会话 . 使用jQuery Ajax,我进行了调用,并在成功的HTTP状态201上将用户重定向到其他页面 . 但是一旦重定向到其他页面,似乎我的会话终止了 .

现在 how can i use the session created by server and make the user to navigate through the site and once he clicks logout. The session should be over.?

在PHP中,我们可以使用$ _SESSION来处理这些事情,并在每个页面中调用此会话变量来检查会话 . 因此,如果它不在那里,我们可以重定向用户登录或显示一些消息,说明会话结束 .

但我想用jQuery做到这一点,我根本不想使用PHP . 我怎样才能做到这一点 .

这是我的形式snippit .

<form id="login-form" action="http://192.168.52.166:6000/api/2/users/login/" method="post">

<p><label for="email">Email</label>
<input type="email" name="email" id="email"></p>

<p><label for="password">Password</label>
<input type="password" name="password" id="password"></p>

<button value="Submit" type="submit">Login</button>
</form>

这是我的jQuery snippit

$('form').on('submit', function(event) {

    var data = {}
    $(this).serializeArray().map(function(x) {
        data[x.name] = x.value;
    });

    $.ajax({
        url: $(this).attr('action'),
        method: $(this).attr('method'),
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'json',
        statusCode: {
            404: function() {
                $("div.error-notif").show();
            },
            201: function() {
                top.location.href = 'page.html';
            }
        },
        success: function(response) {
            console.log(response);
            jsonString = JSON.stringify(response);
            obj = JSON.parse(jsonString);
            $('div#json-response').append(obj.auth_token);
            $("div.success-notif").show();
            $("div.error-notif").hide();
            Cookies.set("authtoken", obj.auth_token);
            alert(Cookie("authtoken"));
        },
        complete: function(xhr, status) {
            console.log(status);
        }
    });

    return false;
});

注意:我正在使用JS Cookie设置auth令牌,该令牌在服务器响应时收到 .

这是请求和回复,取自Wireshark .

POST /api/2/users/login/ HTTP/1.1
Host: 192.168.52.166:6000
User-Agent: curl/7.47.0
Accept: */*
content-type: application/json
Content-Length: 57

{"email":"emjimadhu@email.com", "password":"qwerty123"}

HTTP/1.1 201 CREATED
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 13 Nov 2016 22:00:22 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: POST, OPTIONS
Set-Cookie: csrftoken=CSRF_TOKEN; expires=Sun, 12-Nov-2017 22:00:22 GMT; Max-Age=31449600; Path=/
Set-Cookie: sessionid=6ob5doyoup7roob1o6o0burotayn4yt2; expires=Sun, 27-Nov-2016 22:00:22 GMT; httponly; Max-Age=1209600; Path=/

21b
 {"auth_token":"my auth token", "id":"5f7g5a6r-6q9b-4544-91ce-f79e57d7e2ca","email":"emjimadhu@email.com"}

现在我不知道接下来该做什么 . 让我再次重新解析我的问题 .

1)我想使用表单中的值调用API进行登录 . 如果用户是真实的,服务器应该使用JSON中的响应进行侦听 . (我已经完成了它 . )

2)现在登录后,我需要将用户重定向到其他页面 . 我也用状态代码完成了它 .

3)但是,一旦我重定向,我必须让会话停留,以便用户可以在网站上工作,直到他/她点击注销 .

我该怎么做?

如果我的问题不明白,请告诉我 . 我会尽力解释清楚 .