0

I want to use ajax to retrieve some JSON from another page, but I want to pass along the same GET params that were used to request the original page. How do I do that? Does JS store them in a dict somewhere? Or is there a jQuery solution?

$.ajax({
    url: 'mysecretwebpage.com/supersecret',
    data: ???
});
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 1
    possible duplicate of [Get QueryString values with jQuery](http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery) – mpen Oct 28 '10 at 07:18

3 Answers3

3

The data you need you'll find in

window.location.search

Remove the first char from this string(will be the question mark, if GET is not empty)

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • I also want to add a value... I can append it to the string, but what if it already exists? I'd need to replace it. – mpen Oct 28 '10 at 00:54
  • Ususally it does'nt matter. If you append a key onto a QUERY_STRING, which is already inside, only the last occurance should be considered by the recipient. Assuming a QUERY_STRING like `a=1&a=2&a=3` on the serverside GET['a'] will be 3 – Dr.Molle Oct 28 '10 at 01:11
2

I got this handy function:

document.getParameterByName = function (name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
};

Use it like:

var paramValue = document.getParameterByName('paramName');
Slappy
  • 4,042
  • 2
  • 29
  • 41
  • Don't really want a single param name... I want a dict. And I'm pretty sure you yoinked that off the net somewhere.. at least link back to the article you stole it from. – mpen Oct 28 '10 at 07:16
1

turns out this has been asked before

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236