了解Laravel和cookies

时间:2014-04-09 10:57:11

标签: javascript cookies laravel

这是我第一次使用cookies和Laravel。我正在尝试存储一个简单的值sectionID,并为用户检索它,以便他们可以继续使用上次访问过的部分。如果没有保存的值,我想返回0。

服务器端路由:

Route::get('cookieget', function() {
    return Cookie::get('sectionID', 0);
});

Route::post('cookieset', function() {
     Cookie::make('sectionID', Input::get('sectionID'), 60*24);
});

客户端非常复杂,但这些是相关部分:

UserController.js

function UserController(userID) {
    var outer = this;

    ...

    this.setCookie = function(maxUserSectionID) {

        $.ajax({
            type: 'POST',
            url: "cookieset",
            data: {
                sectionID: maxUserSectionID
            },
            success: function(data) {
                console.log("Set max sectionID cookie to " + maxUserSectionID);
            }
        });
    }

    this.getSectionIDFromCookie = function() {
        $.ajax({
            type: 'GET',
            url: "cookieget",
            async: false,
            success: sectionController.handleNewSection
        });


    }
}

SectionController.js

function SectionController(editor, lessonNr)
{

    // setup initial data
    // the 0-based index of the current section
    this.currentSection = null;
    // the furthest the user has reached in this lesson
    this.maxSection = 0;
...

    // methods

    this.nextSection = function() {

        if (outer.currentSection > outer.maxSection) {
            outer.maxSection = outer.currentSection;
            userController.setCookie(outer.lessonJSON['sections'][outer.maxSection]['sectionID']);
        }

    ...
    };

    ...

    this.checkCookie = function() {
        userController.getSectionIDFromCookie();
    }

    this.handleNewSection = function(newSectionID) {
        alert(newSectionID);
        outer.currentSection = parseInt(newSectionID);
...
    }

    // called from outside as "constructor"
    this.setup = function() {
        ...
    outer.checkCookie();
    }

}

首先,我的主要问题是cookie总是返回0,即使我确信setCookie被成功调用。

其次,我想知道是否有更优雅的方式呢?我现在假设如果啤酒过快地穿过部分,它会给服务器带来很大的负担。

1 个答案:

答案 0 :(得分:1)

必须使用Cookie返回响应才能正确设置Cookie:

Route::post('cookieset', function() {
    $response = Response::make('Hello World');

    return $response->withCookie(Cookie::make('sectionID', Input::get('sectionID'), 60*24););
});