34

I'm reading the jQuery load documentation and it mentions that I can use load to perform a GET request by passing in extra parameters as a string. My current code with my parameters as key/value pair is:

$("#output").load(
    "server_output.html",
    {
        year: 2009,
        country: "Canada"
    }
);

The above works fine but it's a post request. How can I modify the above to perform a GET request while still using load?

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Thierry Lam
  • 45,304
  • 42
  • 117
  • 144
  • Surround your data object with $.param() $("#output").load("server_output.html", $.param({year: 2009, country: "Canada"})); – Bastiaan Linders Feb 25 '14 at 12:34
  • @BastiaanLinders You should mark this as a full answer. It should be combined with the accepted answer which does not describe how to create the params string. – Amala Jan 09 '16 at 18:26

5 Answers5

104

Use $.param(data):

$("#output").load(
    "server_output.html?" + $.param({
        year: 2009,
        country: "Canada"})
);
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Kane
  • 1,420
  • 2
  • 8
  • 5
17

According to the documentation you linked:

A GET request will be performed by default - but if you pass in any extra parameters in the form of an Object/Map (key/value pairs) then a POST will occur. Extra parameters passed as a string will still use a GET request.

So the simple solution is to convert your object to a string before passing it to the function. Unfortunately, the documentation doesn't specify the format the string should be in, but I would guess it would be the same as if you were generating the GET request manually.

$("#output").load(
    "/server_output.html?year=2009&country=Canada"
);
TJ L
  • 23,914
  • 7
  • 59
  • 77
-1
$("#output").load("server_output.html?year=2009&country=Canada");
saturdayplace
  • 8,370
  • 8
  • 35
  • 39
-1

can you not just do:

$("#output").load(
    "server_output.html?year=2009&country='Canada'"
);
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
-2

Use this

$("#output").load("server_output.html", {"2009":year, "Canada":country});
cweston
  • 11,297
  • 19
  • 82
  • 107
Gua Syed
  • 177
  • 1
  • 5