簡體   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