开发者

JavaScript: get original query string when url is rewritten

My page's url is rewritten like so,

www.test-me.com/book-cat-white.HTML

  • book is book.php
  • cat is animal=cat
  • white is color=white

The original URL is

www.test-me.com/book.php?an开发者_运维技巧imal=cat&color=white

With PHP, I can get the values using $_GET, e.g. $_GET['animal']. How can I do the same in JavaScript? Is there a variable I can access that will return the query string?


You can use window.location and its properties however, this only points to http://WWW.test-me.com/book-cat-white.HTML -- The server side rewritten GET parameters will not be available to you.

You could try:

var match = window.location.pathname.match(/\/book-([^-]+)-([^-]+).html$/i);
// for your example - match contains: ["/book-cat-white.HTML", "cat", "white"]

A little further explanation of the Regular Expression:

/         # Start Expression
 \/book-   # Match '/book-'
 (         # Start Capture Group 1
  [^-]+     # Match any character other than '-' 1 or more times
 )         # End Capture Group 1
 -         # Match '-'
 (         # Start Capture Group 2
  [^-]+     # Match any character other than '-' 1 or more times
 )         # End Capture Group 2
 .html     # Match '.html'
 $         # Match the end of the string
/i        # End Expression - Case insensitive flag


You can query the GET string, but only the "public", rewritten one because that's what the browser sees.

If you need the internal, processed, un-rewritten parameters, I would recommend writing them out in the head from within PHP:

<script type="text/javascript">
query_animal = "<?php echo htmlspecialchars($_GET["animal"]); ?>";
query_color = "<?php echo htmlspecialchars($_GET["color"]); ?>";

</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜