简体   繁体   English

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

[英]PHP variable transfer from one page to another

I am building a game on html5(phaser js) for which i need to build a leaderboard. 我正在html5(phaser js)上构建游戏,为此我需要构建排行榜。 the code snippet is this: 代码段是这样的:

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);
},

in the window.open function i wish to pass the value of score to another page where i will ask for the player's name and then insert both the score and the name to the database. 在window.open函数中,我希望将score的值传递到另一个页面,在该页面中我将询问玩家的名字,然后将score和名字都插入数据库中。 But i am having trouble passing the score value across three pages. 但是我无法在三页之间传递分数值。 How can i do this? 我怎样才能做到这一点? Do I need AJAX or just PHP and Javascript is sufficient? 我需要AJAX还是仅PHP和Javascript就足够了?

Can you use browser cookie? 可以使用浏览器cookie吗? you can save score value in cookie and access it whenever you need? 您可以将得分值保存在Cookie中,并在需要时访问它? Read this on how to use cookies link https://developer.mozilla.org/en-US/docs/Web/API/document.cookie 阅读有关如何使用cookie的链接https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

To save to cookie like this: 像这样保存到cookie:

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

In PHP you can read cookie 在PHP中,您可以读取Cookie

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

To Read cookie in JS: 要在JS中读取Cookie:

var score = document.cookie;

You may use the session variable for keeping the variable in the memory and it will be accessible untill your session is alive. 您可以使用会话变量将变量保存在内存中,直到会话有效之前,该变量才可以访问。

<?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));
?>

For more information look here Here 欲了解更多信息,请点击这里

Find jQuery 查找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 save_score.php

session_start();

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

other_page.php other_page.php

session_start();
var_dump($_SESSION);

You can use the $_SESSION variable in php to keep track of user related data in a session. 您可以在php中使用$ _SESSION变量来跟踪会话中与用户相关的数据。 It requires cookies. 它需要cookie。

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

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