简体   繁体   English

当其他内容附加到网址片段后,我该如何使用它们?

[英]How do I use url fragments when other things get appended to them?

I have built a website that displays one table record at a time. 我建立了一个网站,一次显示一个表记录。 I have been using a URL fragment identifier (everything after the first #) to supply the record identifier, so to display the record with identifier '1', the URL would be: baseurl.org/record.html#1 我一直在使用URL片段标识符(第一个#之后的所有字符)来提供记录标识符,因此要显示带有标识符“ 1”的记录,URL为:baseurl.org/record.html#1

In the code, I simply take window.location.hash, strip the leading #, and then query the table for the appropriate record identifier. 在代码中,我只是将window.location.hash除去开头的#,然后在表中查询适当的记录标识符。

I recently found that certain URL shorteners will append things to the end of the URL, so some social media links to my site had '?platform=hootsuite' added to the end. 我最近发现某些URL缩短器会将内容附加到URL的末尾,因此指向我网站的某些社交媒体链接在末尾添加了“?platform = hootsuite”。 Of course, my javascript can't find a record with the identifier '1?platform=hootsuite' 当然,我的JavaScript找不到标识符为'1?platform = hootsuite'的记录

It's easy enough to write a short piece of javascript to extract the substring before a question mark, since I do not expect a question mark in my identifiers. 编写一小段javascript来提取问号之前的子字符串非常容易,因为我不希望标识符中出现问号。 The identifiers sometimes include letters as well, like 22a or 223C, but never special characters like ?, /, &, or #. 标识符有时也包括字母,例如22a或223C,但从不包含特殊字符,例如?,/,&或#。 I am wondering what other unexpected strings could be appended to my URL. 我想知道还有哪些其他意外字符串可以附加到我的URL中。 I guess that anything appended would have to be preceded by a special character like a question mark, so I could come up with a list of special characters and ignore anything after those. 我想添加的任何内容都必须带有特殊字符(如问号),因此我可以列出一系列特殊字符,然后忽略所有特殊字符。

Is there a correct or conventional way to use the URL fragment and to handle things being appended to it? 是否存在使用URL片段并处理附加到URL片段的正确或常规方法? Are there other issues that might arise related to this simple way of using the URL fragment? 与使用URL片段的这种简单方法有关的其他问题可能还会出现吗?

I'm just using html, javascript, and jQuery, and am not interested in a whole separate framework or library to handle this. 我只是使用html,javascript和jQuery,并且对整个单独的框架或库来处理它不感兴趣。

Should only have to worry about ? 应该只需要担心? and just parse your hash between # and first instance of ? 和公正的分析之间的散列#和初审?

var hash = location.hash;
if(hash.length > 1){
  hash = hash.replace(/#|\?.+/g,'');// remove `#` and anything including and after `?`
  // do whatever with your hash records 
}

To be on the safe side I suggest you also send any mismatches to your server and store the url for analysis and future tweaks 为了安全起见,我建议您也将任何不匹配项发送到服务器,并存储该URL以进行分析和将来的调整

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM