开发者

How to correctly read Javascript hash in custom affiliate URL?

I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!

Now, how would I read the following URL?

www.mydomain.com/seo-friendly-url#ref=john
开发者_运维技巧

After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to

www.mydomain.com/seo-friendly-url

Any help is greatly appreciated!


Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).


The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:

To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john

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

... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.

(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜