Ace编辑器 - 通过POST在服务器上保存/发送会话

Pet*_*ter 5 javascript php variables session ace-editor

我写在线网页编辑器,我想在服务器上保存当前视图/工作,以便将来恢复.我也想做多个标签.

我知道,那是editor.getSession()editor.setSession().

JS:

var editor = ace.edit("description");
editor.session.setMode("ace/mode/javascript");
editor.setTheme("ace/theme/tomorrow");
editor.setShowPrintMargin(false);
editor.setOptions({
    enableBasicAutocompletion: true,
    enableSnippets: true
});
Run Code Online (Sandbox Code Playgroud)

现在我尝试通过jQuery将session保存$.data()到元素:

$('#tab1').data('sesi',editor.getSession()); //save session
editor.setSession($('#tab2').data('sesi')); //restore other session
Run Code Online (Sandbox Code Playgroud)

但是这段代码不起作用.当我尝试时,console.log(editor.session);我在控制台中看到了很多代码.

我尝试session通过POST数据发送到服务器,但在网络控制台中,我只看到来自编辑器的代码,仅此而已......

$.ajax({
    type: "POST",
    url: "aaaaa.php",
    cache: false,
    timeout: 10000,
    data: "session="+ editor.session
});
Run Code Online (Sandbox Code Playgroud)

如何将会话保存到变量或服务器?

a u*_*ser 6

要将会话保存到服务器,您需要将其转换为可以传递给json.Stringify的普通对象.session="+ editor.session在您的示例中,只调用session.toString,它与session.getValue相同

var filterHistory = function(deltas){ 
    return deltas.filter(function (d) {
        return d.group != "fold";
    });
}

sessionToJSON = function(session) {
    return {
        selection: session.selection.toJSON(),
        value: session.getValue(),
        history: {
            undo: session.$undoManager.$undoStack.map(filterHistory),
            redo: session.$undoManager.$redoStack.map(filterHistory)
        },
        scrollTop: session.getScrollTop(),
        scrollLeft: session.getScrollLeft(),
        options: session.getOptions()
    }
}

sessionFromJSON = function(data) {
    var session = require("ace/ace").createEditSession(data.value);
    session.$undoManager.$doc = session; // workaround for a bug in ace
    session.setOptions(data.options);
    session.$undoManager.$undoStack = data.history.undo;
    session.$undoManager.$redoStack = data.history.redo;
    session.selection.fromJSON(data.selection);
    session.setScrollTop(data.scrollTop);
    session.setScrollLeft(data.scrollLeft);
    return session;
};
Run Code Online (Sandbox Code Playgroud)

现在要获得会话的状态了

var session = editor.session
var sessionData = sessionToJSON(session)
$.ajax({
    type: "POST",
    url: "aaaaa.php",
    cache: false,
    timeout: 10000,
    data: JSON.stringify(sessionData)
});
Run Code Online (Sandbox Code Playgroud)

并从服务器恢复它

var session = sessionFromJSON(JSON.parse(ajaxResponse))
editor.setSession(session)
Run Code Online (Sandbox Code Playgroud)