3

I need to catch a callback in my razor view page from some social service API. The callback request is implemented by HTTP GET method:

http://www.contactsimporter.com/home.cshtml

After callback is implemented I need to retrieve parameters (param1=value1&param2=value2) from HTTP GET request. For example:

http://www.contactsimporter.com/home.cshtml?param1=value1&param2=value2

I need to retrieve this parameters param1=value1&param2=value2 from callback URL.

How can I get those parameters using JavaScript or jQuery code?

halfer
  • 19,824
  • 17
  • 99
  • 186
Michael
  • 13,950
  • 57
  • 145
  • 288
  • What do you mean "catch a callback?" – Wade Anderson Oct 25 '14 at 17:57
  • 'some social service api' call for your application action with parameters? why you want ta parse query string from view? why not from action method? – aleha_84 Oct 25 '14 at 18:43
  • I think you need to read query string params, have a look at this: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Omu Oct 26 '14 at 20:22

4 Answers4

8

You can achieve it by pure javascript. Refer below code to do so :

var urlParams = window.location.search
var getQuery = urlParams.split('?')[1]
var params = getQuery.split('&') 
Engineer
  • 8,529
  • 7
  • 65
  • 105
7

Adapted from CSS-Tricks

  • To access to the url: window.location.pathname

Now you can treat the url like a normal string in Javascript and parse it accordingly.

var url = window.location.pathname
var getQuery = url.split('?')[1]
var params = getQuery.split('&') 
// params is ['param1=value', 'param2=value2'] 
Wade Anderson
  • 2,461
  • 1
  • 20
  • 22
1

You can also use URLSearchParams

const urlParams = new URLSearchParams(window.location.search);
const entries = urlParams.entries();
// build params object
const params = {};
for (entry of entries) {
  params[entry[0]] = entry[1];
}
console.log(params);
Leon
  • 361
  • 3
  • 8
1

Avoid using window.location.pathname It only return the path You also need the query string parameters, so instead pathname, use href as follow

var url = window.location.href
var getQuery = url.split('?')[1]
var params = getQuery.split('&') 
// params is ['param1=value', 'param2=value2']