Javascript函数在本地服务器上运行但不在线

时间:2014-06-23 00:14:28

标签: javascript html cookies local

所以我有这个javascript游戏可以在我的本地服务器上运行但是一旦我把它上线,其中一个功能就停止了。它可能与我为高分存储的cookie的权限有关。有人可以指出可能出错的地方。

    //Save Highscore if score is greater
 function saveScore() {
     loadScore();
     if (score > highscore) {
         var date = new Date();
         date.setMonth(date.getMonth() + 5);
         var expires = "; expires=" + date.toGMTString();
         document.cookie = "score=" + score + expires + "; path=/";
     }
 }

 //Load High Score
 function loadScore() {
     var cookiearray = document.cookie.split(';');
     for (var i = 0; i < cookiearray.length; i++) {
         var name = cookiearray[i].split('=')[0];
         var value = cookiearray[i].split('=')[1];
         if (name == "score") {
             //alert("Score Found!");
             highscore = value;
         }
     }
     return highscore;
 }

 //Lost game function
 function Lost() {
     saveScore();
     loadScore();
     var lost = document.getElementById("lost");
     var hs = document.getElementById("hs");
     lost.style.visibility = "visible";
     postscore.innerHTML = score;
     hs.innerHTML = highscore;
     lost.addEventListener('click', function (event) {
         window.location.reload();
     });
 }

1 个答案:

答案 0 :(得分:0)

根据您的评论,我猜测您已经修改过您的代码,但由于必须拥有一个已保存的Cookie,因此我们总是有一个已保存的Cookie。在您的代码示例中,如果Cookie不存在,则在使用之前永远不会分配highscore。你应该有一些在页面加载时运行的函数来查找cookie,如果它不存在,则将开始状态初始化为已知值。

此外,我建议面向对象的方法可能更强大。特别是,我创建了一个用于cookie处理的专用对象 - 它可以正确处理cookie不存在的情况 - 以及一个单独的对象或游戏对象。

来自MDN - Cookie处理程序的一个示例

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

作为对象的游戏元素的一个潜在实现,加载到使用上面的cookie处理程序的立即调用的函数中。

(function(cookieHandler) {
    // Game constructor
    var Game = function(cookieHandler) {
        this.init(cookieHandler);
    };

    // initializes the game variables, sets up and binds the event handlers
    Game.prototype.init = function(cookieHandler) {
       this.scoreCookie = 'score';
       this.score = 0;
       this.highScore = this.loadScore();
       this.cookieHandler = cookieHandler;
       this.lostElem = document.getElementById("lost");
       this.postScoreElem = null; // don't see this defined anywhere
       this.highScoreElem = document.getElementById("hs");

       this.setUpHandlers()
           .bind();
    };

    // create handlers for the events
    Game.prototype.setupHandlers = function() {
        this.lostHandler = this.lost.bind(this);
        return this;
    };

    // bind the handlers to events
    Game.prototype.bind = function() {
        // there should probably be a binding for some event
        // to invoke the lost handler (lostHandler)
        this.lostElem.addEventListener('click', function (event) {
            window.location.reload();
        });
    };

    // save the current score, if higher than the current high score, to
    // the game cookie
    Game.prototype.saveScore = function() {
        if (this.score > this.highScore) {
            var date = new Date();
            date.setMonth(date.getMonth() + 5);
            this.cookieHandler.setItem(this.scoreCookie, score, date, '/');
        }
    };

    // retrieves the high game score from the cookie, initializes it to zero
    // if there is no cookie.
    Game.prototype.loadScore = function () {
        this.highScore = 0;
        if (this.cookieHandler.hasItem(this.scoreCookie)) {
            this.highScore = parseInt(this.cookieHandler.getItem(this.scoreCookie,10);
        }
    };

    // when the game is lost, update the high and save the current score
    // if it is a new high score.  Signal that the game was lost.            
    Game.prototype.lost = function() {
        this.loadScore();
        this.saveScore();
        this.lostElem.style.visibility = "visible"
        // this.postScoreElem.innerHTML = score;
        this.highScoreElem.innerHTML = highscore;
    };

    var game = new Game(docCookies);
)(docCookies);