【问题标题】:How to correctly read Javascript hash in custom affiliate URL?如何正确读取自定义会员 URL 中的 Javascript 哈希?
【发布时间】:2011-09-24 06:07:56
【问题描述】:

我正在创建一个自定义联属网络营销计划。我希望我的链接尽可能对 SEO 友好,因此我将使用附加到 URL 的 Javascript 哈希来发送会员 ID、读取会员 ID、存储点击,然后 301 重定向到他们链接的页面也。这样我们就没有任何规范问题,并且每个附属链接都通过链接汁!

现在,我将如何阅读以下网址?

www.mydomain.com/seo-friendly-url#ref=john

获取 ref 的哈希值并添加点击后,我将如何 301 将用户重定向回

www.mydomain.com/seo-friendly-url

非常感谢任何帮助!

【问题讨论】:

    标签: javascript hash affiliate


    【解决方案1】:

    片段标识符(# 后面的部分)不会发送到服务器,因此任何可能发出 HTTP 响应(301 重定向需要它)的东西都无法读取它们。

    【讨论】:

    • 我尝试过使用常规变量,例如 www.mydomain.com/seo-friendly-url?ref=john 但由于某种原因,我的 php 附属检查脚本没有读取它们。是因为我使用的是 htaccess 发送的 seo 友好的 url?
    【解决方案2】:

    URL 的“哈希”部分不会传递给服务器,因此您将无法直接利用这些数据进行任何服务器端重定向或处理。但是,可以在页面加载时获取哈希并通过 AJAX 或重定向将其传递给服务器:

    立即将用户从www.mydomain.com/seo-friendly-url#ref=john 重定向到www.mydomain.com/seo-friendly-url/ref/john

    if (window.location.hash.match(/#ref=/))
        window.location = window.location.href.replace('#ref=', '/ref/')
    

    ...但是,为什么不直接使用www.mydomain.com/seo-friendly-url/ref/john 开始并节省额外的腿部工作呢?另一条途径是通过 AJAX,涉及在页面加载后读取哈希值并将其发送到服务器进行记录。

    (注意:此代码使用 generic cross-browser XMLHTTPRequest 发送 AJAX GET 请求。替换为您的库的实现 [如果您使用的是库])

    window.onload = function () {
        // grab the hash (if any)
        var affiliate_id = window.location.hash;
        // make sure there is a hash, and that it starts with "#ref="
        if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
            // clear the hash (it is not relevant to the user)
            window.location.hash = '';
            // initialize an XMLRequest, send the data to affiliate.php
            var oXMLHttpRequest = new XMLHttpRequest; 
            oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
            oXMLHttpRequest.onreadystatechange = function() { 
                if (this.readyState == XMLHttpRequest.DONE) { 
                    // do anything else that needs to be done after recording affiliate
                } 
            }
            oXMLHttpRequest.send(null);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2017-06-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多