在ajax调用之后访问post变量

时间:2016-09-21 03:17:11

标签: javascript php jquery ajax

在我的应用程序中,我有一个AJAX调用,在用户重新加载页面之前将用户的时区(到同一页面)发布(以查看他们是否切换了时区)。不幸的是,我无法访问该post变量。

$(window).on('beforeunload', function() {
    $.ajax({
        type: "POST",
        url: "ToDoApp.php",
        data: {
            timezone: userTimeZone
        },
        dataType: 'text'
    });
});

我很确定这是因为我在AJAX调用期间重新加载一次,其次是页面实际重新加载。但是,我已经在圈子里走了一个小时,似乎无法解决我的问题。

如何在页面重新加载后获取时区变量?

如果有更好的方法可以完全解决问题,我愿意接受建议。

更多信息:

我需要服务器端的时区变量来执行时区转换,因此我的AJAX调用。从我的评论如下:

  

所以这就是困境:我意识到时区是更好的计算客户端   我正在用Moment.JS做的一面,但我需要时区变量   进行服务器端时区转换以正确显示日期   用户。这就是为什么我[认为我]需要一个AJAX调用,因为没有它   一旦页面重新加载我的时区将只在客户端上提供   我和我都无法进行计算。

3 个答案:

答案 0 :(得分:1)

您可以使用javascript的sessionStorage ...执行以下操作..

//set this anywhere you want in your .js script;
sessionStorage.setItem('TheTimeZone',userTimeZone);

//get the timezone using sessionStorage
$(window).on('beforeunload', function() {
    $.ajax({
        type: "POST",
        url: "ToDoApp.php",
        data: {
            timezone: sessionStorage.getItem('TheTimeZone')
        },
        dataType: 'text'
    });
});

这应该有效。

答案 1 :(得分:0)

你做不到。您必须编写应用程序才能在回调中访问userTimeZone值。也许只是在请求结果中返回请求变量?这样我建议使用JSON代替文本格式。您可以从脚本返回 ToDoApp.php

echo json_encode(array('post'=>$_POST, result=>$result));

并在回调中访问它们,如:data.post,data.result。

答案 2 :(得分:0)

$(window).on('beforeunload', function() {
    if (typeof(Storage) !== "undefined") {
      localStorage.setItem("timeZone",new Date().getTimezoneOffset());
    } else {
      // Sorry! No Web Storage support..
    }
    $.ajax({
        type: "POST",
        url: "ToDoApp.php",
        data: {
            // new Date().getTimezoneOffset() gives clients timezone
            timezone: localStorage.getItem("timeZone")
        },
        dataType: 'text'
    });
});

了解更多:w3school on timezone

相关问题