繁体   English   中英

PHP变量从一页转移到另一页

[英]PHP variable transfer from one page to another

我正在html5(phaser js)上构建游戏,为此我需要构建排行榜。 代码段是这样的:

restart_game: function() {  
// Start the 'main' state, which restarts the game
//this.game.time.events.remove(this.timer);  
    //this.game.time.events.remove(this.timer2);  
    //this.game.state.start('main');
    var string="score.php?score="+this.score;
    window.open(string);
},

在window.open函数中,我希望将score的值传递到另一个页面,在该页面中我将询问玩家的名字,然后将score和名字都插入数据库中。 但是我无法在三页之间传递分数值。 我怎样才能做到这一点? 我需要AJAX还是仅PHP和Javascript就足够了?

可以使用浏览器cookie吗? 您可以将得分值保存在Cookie中,并在需要时访问它? 阅读有关如何使用cookie的链接https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

像这样保存到cookie:

document.cookie="score=54; expires=Thu, 18 Dec 2013 12:00:00 GMT";

在PHP中,您可以读取Cookie

if(isset(($_COOKIE['score'])) {
    $score = $_COOKIE['score'];
}

要在JS中读取Cookie:

var score = document.cookie;

您可以使用会话变量将变量保存在内存中,直到会话有效之前,该变量才可以访问。

<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
    $session = eval("return {$_POST['session']};");
    if (is_array($session)) {
        $_SESSION = $session;
        header("Location: {$_SERVER['PHP_SELF']}?saved");
    }
    else {
        header("Location: {$_SERVER['PHP_SELF']}?error");
    }
}

$session = htmlentities(var_export($_SESSION, true));
?>

欲了解更多信息,请点击这里

查找jQuery

restart_game: function() {  
  var score = this.score;
  $.ajax({
    url: 'save_score.php',
    data: {score: score},
    method: 'POST'
  }).done(function() {
    window.location = "other_page.php";
  });
},

save_score.php

session_start();

if(isset($_POST['score']) && strlen($_POST['score']) > 0) {
  $score = intval($_POST['score']);
  $_SESSION['score'] = $score;
}

other_page.php

session_start();
var_dump($_SESSION);

您可以在php中使用$ _SESSION变量来跟踪会话中与用户相关的数据。 它需要cookie。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM