如何在多个php页面中保持js变量值

时间:2016-02-03 05:10:34

标签: javascript

index.js // linked to all php files.
var pass;
console.log(pass); // undefined

$("#btn").click(function() {
    pass = "323";
    location.href = "test.php";
});

转到test.php console.log再次显示undefined 我需要在所有网页上保留pass值为323,一旦建立完毕。

2 个答案:

答案 0 :(得分:1)

最简单的方法:使用localStorage

如果您只需要存储字符串:

var pass = localStorage.pass;

$("#btn").click(function() {
    pass = "323";
    localStorage.pass = pass;
    location.href = "test.php";
});

或者,请注意localStorage会将您存储的所有内容更改为字符串。因此,如果您想存储对象,数字等,则需要JSON.stringify

// index.js
if (localStorage.pass === undefined)
    localStorage.pass = "null";
var pass = JSON.parse(localStorage.pass);

$("#btn").click(function() {
    pass = "323";
    localStorage.pass = JSON.stringify(pass);
    location.href = "test.php";
});

答案 1 :(得分:1)

您可以使用该会话在所有页面上顺利运作。

var pass;
console.log(pass); // undefined

$("#btn").click(function() {
   pass = "323";
   $.post('savesession.php','pass='+pass,function(){
       console.log("session saved");
       location.href = "test.php";
   });
});

<强> savesession.php

<?php
session_start();
$pass = $_POST['pass'];
$_SESSION['pass'] = $pass;

<强> anypage.php

<?php
session_start();
$pass = $_SESSION['pass'];