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,涉及在页面加载后读取哈希值并将其发送到服务器进行记录。
(注意:此代码使用通用的跨浏览器 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);
}
}