如何从大型js文件传递单个变量?

时间:2014-07-29 08:20:43

标签: javascript jquery

index.js

$(window).resize(function(){
    var page = location.pathname.split('/').slice(-1)[0];
    if (page != "minw.php") {goback = location.pathname;}
    var w1 = document.documentElement.clientWidth;
    var minw = 800;
    if (w1 < minw) {location.href = '../minw.php'};
});

minw.php我有一个按钮并点击它我想转到goback地址。

但是index.js是一个非常大的文件,在minw.php上我只需要一个变量 - goback

有没有办法在minw.php内只获取此变量而不链接整个index.js而不创建一个新的js文件只是为了包含这个变量?

可能就像在$_SESSION中传递php变量一样?

2 个答案:

答案 0 :(得分:1)

您可以使用GET变量:

if (w1 < minw) {location.href = '../minw.php?goBack=' + yourGoBackVarHere};

然后从PHP中读取它:

$goBack = $_GET['goBack'];

如果您不想使用GET查询弄乱URL,那么使用会话当然会有效。

答案 1 :(得分:1)

如果要将变量存储在sessoin中,请使用ajax&amp;将你的varibale发送到php文件(minw.php或其他)&amp;将变量保存在会话中..

jQuery.ajax({
    url: 'savesession.php',
    type: 'POST',
    data: {
        txt: 'goback',
    },
    dataType : 'json',
    success: function(data, textStatus, xhr) {
        console.log(data); // do with data e.g success message
    },
    error: function(xhr, textStatus, errorThrown) {
        console.log(textStatus.reponseText);
    }
});

在php文件中

$_SESSION['goback'] = $_POST['txt'];