【问题标题】:How to use Ajax to pass Javascript variables to Coldfusion?如何使用 Ajax 将 Javascript 变量传递给 Coldfusion?
【发布时间】:2012-05-22 16:48:57
【问题描述】:

我需要使用 Javascript 来检测本地用户的 UTC 偏移量,然后在我的 cfquery 中为我的大型网站的其余部分使用该 UTC 偏移量。

这是我想运行的自上而下的逻辑。我只需要帮助将 Javascript 中的 Javascript 数据(UTC 偏移量)设置为 Coldfusion 变量,以便可以在我的 cfquery 的 SQL 中使用它。

1.) 页面加载 2.) Ajax 调用简单的 Javascript 来获取用户的 UTC 偏移量 3.) 在 Coldfusion 变量中返回 UTC 偏移量 4.) 在 SQL cfquery 中使用 Coldfusion 变量来调整 UTC 日期以适应用户的时区。

【问题讨论】:

  • 看看我对类似问题的回答:stackoverflow.com/a/9541365/808921
  • 很遗憾,我无法在我们的共享主机 Web 环境中使用会话变量。还有其他建议吗?
  • 我的其他答案指的是会话结构这一事实并没有改变基本方法。再看看。

标签: javascript ajax coldfusion


【解决方案1】:

一种可能的方法是使用 JavaScript 在他们点击的第一页上设置时间戳 cookie。然后在后续页面中使用 cfcookie 引用该 cookie。

var curDateTime = new Date();
var tzoffset = "-" + (curDateTime.getTimezoneOffset()/60);
var expiredate = new Date();
expiredate.setTime(expiredate.getTime()+(120*24*60*60*1000)); // set expire date to 120 from now
document.cookie = "local_tz="+tzoffset+";expires="+expiredate.toGMTString();

【讨论】:

  • 谢谢,但我希望尽可能避免使用 cookie 并使用 Ajax 解决方案。
  • 这必须有多可靠?您可以将用户偏移量与客户端 IP 地址一起保存在数据库表中。这会产生一些开销,因为您将在每个页面请求上运行 UDF/查询。不推荐或最佳实践,但它可能适用于您的特定设置。
【解决方案2】:
  1. 首先获取偏移量并发送到coldfusion cfc(假设您使用jquery js库)

    var offsetmin = new Date().getTimezoneOffset(); //分钟 var offsethr = offsetmin/60; //小时

    $.ajax({
     type: "POST",
     url: WebRoot + "/pathtocfc.cfc?method=createClientOffset",
     data: "offset="+offsethr,
     dataType: "json"
    }).done(function(result){
        //make sure you saved it successfully with your client ip address
    

    });

  2. 下一步在coldfusion中保存offset和ip

    <cffunction name="createClientOffset" access="remote" returnformat="JSON">
    <cfargument name="offset" >
    
    <!---get ip address from cgi scope--->
    
    <cftry>
      <!---try to save client ip and offset together using cfquery--->
    </cftry>
    
    </cffunction>
    

3.在随后的页面请求中调用 UDF 以尝试获取客户端偏移量或在运行查询以返回日期并从 gmt 日期中减去 utc 偏移量之前进行调用。

    <cffunction name="readoffset" access="public">
    <cfargument name="ipaddress" >

    <!---use cfquery to match ipaddress with offset if it doesn't exist then use a default offset or add logic to create one if it doesn't exist--->


      <cfreturn offset />
    </cffunction>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2016-08-28
    相关资源
    最近更新 更多