简体   繁体   中英

Get query string value on page load fails

NOTE: This page has an older version that works that doesn't use AngularJS.

In my jQuery/javascript file on page load I'm running a function to return a query string value which is returned as an empty string, but value does exist in url. The query string value that gets returned is sent to a switch statement that returns a phone number that will be displayed on page when browser renders.

// Page load/ready
var campaignSub = getParameterByName("sub");
getPhoneNumber(campaignSub);

Then in my html markup, I have my third party script which was provided to me that scans the page looking for the phone number returned from my switch statement and replaces that phone number with a phone number pulled from a recycled pool of phone numbers.

After that my Angular Controller fires and loads a partial view ui.router to display a questionaire.

My Question: Why am I unable to return a simple query string parameter value from my script that is firing first?

The best and optimal way to get query string values using JavaScript . Checkout the below example to fetch the query string.

var queryString = window.location.search || '';
var keyValPairs = [];
var params      = {};
queryString     = queryString.substr(1);

if (queryString.length)
{
   keyValPairs = queryString.split('&');
   for (pairNum in keyValPairs)
   {
      var key = keyValPairs[pairNum].split('=')[0];
      if (!key.length) continue;
      if (typeof params[key] === 'undefined')
         params[key] = [];
      params[key].push(keyValPairs[pairNum].split('=')[1]);
   }
}

Usage of the above script

//url=http://stackoverflow.com/how-to-get-query-string-values-in-javascript?query=123&list=default
params['query'];
//Output ["123"]

params['list'];
//Output ["default"]

//Note: If the query string value is empty the method will return the value as empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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