Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get query string value from script path?

I am adding my Javsacript file in pages with different query strings in the script path like this:

Page1:

<script type="text/javascript" src="file.js?abc=123"></script> 

Page2:

<script type="text/javascript" src="file.js?abc=456"></script> 

Page3:

<script type="text/javascript" src="file.js?abc=789"></script> 

In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.

In case it helps, below is a function I use to find the value of a query string param:

function getQuerystring(key, defaultValue) {     if (defaultValue == null) defaultValue = "";     key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");     var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");     var qs = regex.exec(window.location.href);     if (qs == null)         return defaultValue;     else         return qs[1]; } 
like image 254
TruMan1 Avatar asked Jan 17 '11 18:01

TruMan1


People also ask

How do I get the value of a query string in Wordpress?

To get a vars from the query string you can use PHP's $_GET['key'] method. Depending on what you are doing, you can also use get_query_var('key') , this function works with parameters accepted by the WP_Query class (cat, author, etc).

How do I find the query string of a website?

The PHP Server object provides access to the query string for a page URL. Add the following code to retrieve it: $query_string = $_SERVER['QUERY_STRING']; This code stores the query string in a variable, having retrieved it from the Server object.

How do I pass query string?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


1 Answers

This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered–

var scripts = document.getElementsByTagName('script'); var index = scripts.length - 1; var myScript = scripts[index]; // myScript now contains our script object var queryString = myScript.src.replace(/^[^\?]+\??/,''); 

Then you just apply the query string parsing.

like image 200
Ashley Avatar answered Sep 25 '22 15:09

Ashley