JavaScript:重写url时获取原始查询字符串

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?animal=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>