본문으로 건너뛰기

레슨 29 · AJAX

$.get, $.post, $.getJSON and .load()

Use jQuery's AJAX shortcuts: $.get, $.post, $.getJSON, $.getScript and .load() with fragment selectors, plus $.param serialization, all with runnable stand-ins.

$.ajax() can do anything, but most requests are one of a few common shapes: fetch some JSON, post some values, drop a chunk of HTML into the page. jQuery gives each shape a shorthand that fills in the settings object for you. You write less, and the intent is obvious from the method name.

Every shorthand returns the same jqXHR promise as $.ajax(), so .done(), .fail() and .always() work on all of them. As in the last lesson, the examples include a small stand-in server for URLs beginning with /api/, since the sandbox cannot reach a real one.

Pick the shortcut

$.get GET anything.
$.post POST form-encoded data.
$.getJSON GET and parse JSON.
.load() Put returned HTML into elements.
1 / 2

$.get()

The signature is $.get(url, data, success, dataType). Everything after url is optional, and jQuery works out which argument you passed by its type, so you can skip data.

JavaScript
$.get("/api/greeting.html", function (html) {
  $("#target").html(html);
});

$.get("/api/users", { limit: 2 }, function (users) {
  console.log(users.length);
}, "json");

The second call requests /api/users?limit=2. The object is converted to a query string for you. The fourth argument is dataType; leaving it out lets jQuery guess from the response header.

$.getJSON()

$.getJSON(url, data, success) is $.get() with dataType: "json" fixed, so the callback receives a parsed object. It is the shorthand you will use most for APIs.

JavaScript
$.getJSON("/api/users", { limit: 2 }).done(function (users) {
  users.forEach(function (user) { console.log(user.name); });
});

If the body is not valid JSON, .fail() runs with textStatus "parsererror", just as in $.ajax().

$.post()

$.post(url, data, success, dataType) sends a POST with the data in the body, form-encoded (name=Ada&role=admin).

JavaScript
$.post("/api/users", { name: "Ada", role: "admin" }, function (created) {
  console.log("created id", created.id);
}, "json");

There is no shorthand for sending JSON, PUT or DELETE. For those, go back to $.ajax() and set method and contentType. That is the rule of thumb: shortcuts for the common case, $.ajax() when you need control.

get, getJSON and post, with the real request lines

Notice that $.get without a dataType still returned an object here: the stand-in labels its reply as JSON, and jQuery's guessing used that.

.load(): HTML straight into the page

.load(url, data, complete) is a method on a jQuery collection, not a utility function. It fetches HTML and inserts it into every matched element. If data is an object the request is a POST; with a string or no data it is a GET.

JavaScript
$("#sidebar").load("/api/page.html");
$("#sidebar").load("/api/page.html", function (responseText, textStatus, jqXHR) {
  if (textStatus === "error") { $(this).text("Could not load."); }
});

The callback runs after the content is inserted, for each matched element, with this set to the element. Note that .load() also reports errors through textStatus, rather than a separate error callback.

Loading just a fragment

Add a space and a selector after the URL, and only the matching part of the response is inserted. The server still sends the whole document, so this is a convenience, not a bandwidth saving.

JavaScript
$("#news").load("/api/page.html #latest");

Two behaviors to remember. First, with a fragment selector jQuery parses the HTML and discards <script> tags; without a selector, scripts in the loaded HTML are executed. Second, never .load() a URL that is built from user input, because the returned HTML is inserted as markup (see best practices).

$.getScript()

$.getScript(url, success) fetches JavaScript and runs it in the global scope. It is a tidy way to load an optional feature only when it is needed.

JavaScript
$.getScript("/api/chart-widget.js").done(function () {
  window.ChartWidget.draw("#chart");
});

Unlike a <script> tag, the request bypasses the browser cache by default (jQuery appends a _=timestamp parameter) unless you pass cache: true through $.ajax({ dataType: "script", cache: true, url: ... }). Only load scripts from servers you trust, since they run with full access to your page.

.load() with a fragment selector and $.getScript

Serializing data with $.param()

All of these methods turn the data object into a string with $.param(), and you can call it yourself, for example to build a link or log what will be sent.

JavaScript
$.param({ q: "cats & dogs", page: 2 });
// "q=cats%20%26%20dogs&page=2"

$.param({ tags: ["js", "ui"], user: { id: 7 } });
// "tags%5B%5D=js&tags%5B%5D=ui&user%5Bid%5D=7"   (tags[]=js&tags[]=ui&user[id]=7)

$.param({ tags: ["js", "ui"] }, true);
// "tags=js&tags=ui"      (the "traditional" style)

The default bracket style (tags[]) suits PHP and Rails. Many other servers expect repeated names, which is what the second argument true produces. For a whole form, $("form").serialize() does the same job from the fields' current values; it is covered in Working with Form Controls.

See $.param output

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does $.getJSON('/api/users', { limit: 2 }) request?

    $.getJSON is a GET with dataType json. The data object is converted to a query string.
  2. 2. How do you load only the element with id 'latest' from a fetched page?

    Put a space and a selector after the URL. jQuery fetches the whole page but inserts only the matching part.
  3. 3. Which request cannot be done with the shorthand methods and needs $.ajax()?

    The shortcuts cover GET and form-encoded POST. Other methods and JSON bodies need method and contentType in $.ajax().
  4. 4. What is $.param({ tags: ['js', 'ui'] }, true) used for?

    The second argument selects traditional serialization: repeated names without the [] suffix.

Summary

  • $.get(url, data, success, dataType) and $.post(...) take optional arguments in that order; $.getJSON(url, data, success) parses JSON.
  • Data objects become query strings (GET) or form-encoded bodies (POST) through $.param(); pass true for the traditional, bracket-free style.
  • .load(url selector) inserts returned HTML into the matched elements and can keep just one fragment; fragments drop scripts.
  • $.getScript() loads and runs JavaScript globally; only use trusted sources.
  • All shorthands return the jqXHR promise. Switch to $.ajax() for JSON bodies, PUT/DELETE, headers and fine control.

Now learn what to do with that returned promise in Deferreds, Promises and Ajax Events.

진행 상황 기록

무료 계정을 만들면 레슨을 체크하고, 어떤 기기에서든 하던 곳부터 이어 학습할 수 있어요.